Eloquent relationship - php

As the title suggests, I have a little problem with the relationship between my tables.
Unknown column 'table1.entity_id' in 'where clause'
select * from `table2` where `table1`.`entity_id` = `table2`.`id`
Here is the structure of my tables:
table1
id varchar(36)
type enum()
entity_id varchar(36)
table2
id varchar(36)
description
table3
id varchar(36)
brand
In the table1.entity_id column we can find the id of table2 and table3.
And these are the relationships:
Table 1
public function table2()
{
return $this->hasMany('App/Model/Table2', 'entity_id');
}
public function table3()
{
return $this->hasMany('App/Model/Table3', 'entity_id');
}
Table 2
public function table1()
{
return $this->belongsTo('App/Model/Table1', 'id', 'entity_id');
}
Table 3
public function table1()
{
return $this->belongsTo('App/Model/Table1', 'id', 'entity_id');
}
And when I do that :
$query->orWhereHas('table2', function($query) use ($value) {
$query->whereNotNull('description');
});
I have this error :
Unknown column 'table1.entity_id' in 'where clause'
select * from `table2` where `table1`.`entity_id` = `table2`.`id`
Can someone tell me what is the problem ?

Related

How to query a customize key in Laravel?

Considering this tables: person and employee to which connected to person by person_id. This person_id is also the Primary & Foreign key of employee table. Thus in my migrations, i have this:
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('person_id');
$table->foreign('person_id')->references('id')->on('persons')->onDelete('cascade');
});
and my show method is like this one
public function show(Employee $employee){
dd($employee->person_id);
$employee = Employee::where('person_id', $employee->person_id)->orderBy('employee_number', 'asc')->join('persons', 'employees.person_id', '=', 'persons.id')->first();
return view('employee.show', compact('employee'));
}
But i am experiencing this issue:
Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `employees` where `id` = 5 limit 1)
Does the query is not aware of the column i am using?
Change the primary key in the Employee model
class Employee extends Model
{
/**
* The primary key associated with the table.
*
* #var string
*/
protected $primaryKey = 'person_id';
public function person()
{
return $this->belongsTo('App\Employee', 'person_id', 'person_id');
}
}
Then query using find
Employee::find($employee->person_id)->with('person')->first();
orderBy and first are redundant on one result queries
And if you want to return the Employee with the Person, just access the relationship object (employee is returned from route model binding)
public function show(Employee $employee) {
$person = $employee->person;
return view('employee.show', compact('employee', 'person'));
}
Hope this helps

Search pivot table Eloquent

I have 3 tables
students
- id
- name
classes
- id
- name
student_class
- id
- student_id
- class_id
- score
I want to return a list of the students that belong to class_id = 100
$students = \Student::where(['class_id' => 100])->get();
this is my Student Class
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $table = 'students';
public function store(Request $request)
{
$student = new Student;
$student->save();
}
}
the error I´m getting is:
<strong>Message:</strong> SQLSTATE[42S22]: Column not found: 1054 Unknown column 'class_id' in 'where clause' (SQL: select * from `students` where (`class_id` = 100))
update: I can do
$students = \Class::find(100)->with(['students'])->get();
and it will return all the students as a child of classes but I don´t need that.
I need the data from students and the pivot table (student_class) in particular de score column.
thank you for your help
Update your student model as
public function classes(){
return $this->belongsToMany(Class::class, 'student_class', 'student_id', 'class_id');
}
//query
Student::whereHas('classes', function ($query) {
$query->where('id', 100);
})->get();
UPDATE : in both of your model relation add
return $this->belongsToMany('App\Class')->withPivot('score');
now you can do this inside your loop
foreach ($student->classes as $class) {
echo $class->pivot->score;
}

How to get hasOne property inside view?

How can I echo category name when in Urls view? I get this error:
Column not found: 1054 Unknown column 'categories.url_id' in 'where clause'
(SQL: select * from `categories` where `categories`.`url_id` = 23 and `categories`.`url_id` is not null limit 1
I believe the query should be something like this
SELECT * FROM categories WHERE categories.id = 1
Urls table
id | url | category_id
1 www.asdf.com 1
Categories table
id | category
1 Something
Migration for adding column Category_id to Urls table
public function up()
{
Schema::table('urls', function(Blueprint $table){
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')->on('urls');
});
}
(hm I believe I need to fix this and put references('id')->on('categories') )
Url model
class Url extends Model
{
protected $table = 'urls';
public function category()
{
return $this->hasOne('App\Category');
}
}
Url index controller
$urls = URL::paginate(100)
return view('urls.index')->with('urls', $urls);
Urls.index view
{{ $url->category->category }}
If I change Url model to this
public function category()
{
return $this->belongsTo('App\Category');
}
and when I do var_dump($url->category), the correct SQL query is generated:
select * from `categories` where `categories`.`id` = '1' limit 1
but I still can't get column name with {{ $url->category->category }}
because error is Trying to get property of non-object
Use belongsTo() relationship instead of hasOne():
public function category()
{
return $this->belongsTo('App\Category');
}

Has many through with pivot table

A Venue hasMany Subscription
A Subscription belongsToMany User
How can I retrieve all User from Venue through Subscription?
I imagine something like:
$venue->subscribers // Return all `User`
My database scheme: http://www.laravelsd.com/share/AAjuYS
I have tried
class Venue {
public function subscribers() {
return $this->hasManyThrough('App\User', 'App\Subscription');
}
}
Fails with error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.subscription_id' in 'on clause' (SQL: select `users`.*, `subscriptions`.`venue_id` from `users` inner join `subscriptions` on `subscriptions`.`id` = `users`.`subscription_id` where `users`.`deleted_at` is null and `subscriptions`.`venue_id` = 1)
// In Venue class
public function subscribers()
{
return $this->hasManyThrough('App\User', 'App\Subscription');
}
You can read about it in the documentation, it's pretty straight-forward: http://laravel.com/docs/5.1/eloquent-relationships#Has-Many-Through

Laravel Eloquent ORM filtering with relationship

I'm making a filter and there is a problem that I can't solve. The filter uses relationship and it's perfect. But when I make a filter of attribute that doesn't exist in the table it doesn't work. Because the question was too complicated I will give you an example code:
<?php
class School extends Eloquent {
protected $table = 'schools';
public function city(){
return $this->belongsTo('City');
}
public function municipality(){
return $this->belongsTo('Municipality');
}
public function listSchoolsEndUser()
{
$schools_data = new School;
if ( Input::has('district') ) {
$schools_data = $schools_data->whereHas('city', function($q){
$q->where('district_id', '=', Input::get('district'));
});
}
if ( Input::has('municipality') ) {
$schools_data = $schools_data->whereHas('city', function($q){
$q->where('municipality_id', '=', Input::get('municipality'));
});
}
if ( Input::has('city') ) {
$schools_data = $schools_data->where('city_id', '=', Input::get('city'));
}
$schools_data = $schools_data->paginate(12);
return $schools_data;
}
}
And the error is:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'district_id' in 'where clause' (SQL: select count(*) as aggregate from `schools` where (`specialties` like %"5"%) and (select count(*) from `cities` where `schools`.`city_id` = `cities`.`id` and `district_id` = 5) >= 1)
And the example table structure is:
Schools table:
|---------------|
|id|name|city_id|
|---------------|
Cities table:
|-----------------------|
|id|name|municipality_id|
|-----------------------|
Municipalities table:
|-------------------|
|id|name|district_id|
|-------------------|
Districts table:
|-------|
|id|name|
|-------|
Because district_id is two relations away you need to use the dot syntax to target nested relations:
if ( Input::has('district') ) {
$schools_data = $schools_data->whereHas('city.municipality', function($q){
$q->where('district_id', '=', Input::get('district'));
});
}
(This assumes you have a municipality() relation in your Citymodel)

Categories