I have User Model with Roles relationships like so :
public function users(){
return $this->belongsToMany(User::class)->withTimestamps();
}
And Role Model with user relationships :
public function roles(){
return $this->belongsToMany(Role::class)->withTimestamps();
}
And of course Pivot Table "role_user" contains id, user_id, role_id and timestamps
I try to get users ordered By roles name like so :
$users = App\Models\User::with('roles')->orderBy('roles.name', 'desc')->get();
but i have this error :
Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.name' in 'order clause' (SQL: select * from `users` where `users`.`deleted_at` is null order by `roles`.`name` desc)
http://localhost:8000/users
Please, some helps .
Try Like this:
$users = App\Models\User::with('roles')->get();
// order of the roles
$array = ['User','Admin','Doctor', 'Manager'];
$sorted = $users->sortBy(function($model) use ($array) {
return array_search($model['roles'], $array);
});
Hope it will help you!
Related
I have two tables with the polymorphic relationships.
Invoice Table:
public function transactions(){
return $this->morphMany(TransactionAllocation::class, 'doc');
}
Payment Table:
public function doc()
{
return $this->morphTo();
}
This relationship works fine if I use with.
But when I am trying to use join, this does not work. Related Laravel Doc.
DB::table('invoices')
->join('transactions', function ($join){
$join->on('invoices.id','=','transactions.doc_id')
->where('transactions.doc_type','App\Models\Invoice');
})
->get()
Here is the error I get:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'transactions.doc_id'
in 'on clause' (SQL: select * from `invoices` inner join `transactions`
on `invoices`.`id` = `transactions`.`doc_id`
and `transactions`.`doc_type` = App\Models\Invoice)
I am trying to clean my code up, and working on the Models
I have the following 2 tables broken down like this:
Roll Table
|id|roll_id|member_id|.......
Members table
|id|first_name|last_name|rank|
I have the following on my Roll Model
public function member()
{
return $this->belongsTo('App\Member');
}
This on my Member model
public function roll()
{
return $this->hasMany('App\Roll');
}
While the following code does return the correct results
$roll = Roll::with(['member'])
->where('status', '!=', 'A')
->get();
return ($roll);
I would like to add an extra where clause
->where('rank','<', 12)
However, I get the following error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'member.rank'
in 'where clause' (SQL: select * from Roll where roll_id = 4 and
status != A and `mem ▶"
You can use whereHas method to filter on the relations:
$roll = Roll::with(['member'])
->where('status', '!=', 'A')
->whereHas('member', function($query) {
$query->where('members.rank', '<', 12);
})
->get();
Hope this will resolve your issue.
I try to update field rate in table by primary key user_id.
So, I need to increment of decrement rate field. If row is not exist I need to create it.
I tried:
$this->point = -1; // Or $this->point = 1;
Rating::updateOrCreate(["user_id", $id], ["rate" => $this->point]);
But it does not work:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from `rating` where (`0` = user_id and `1` = 5) limit 1)
This is because your passing the column and the value as two separate values.
Change:
["user_id", $id]
to:
["user_id" => $id]
Hope this helps!
Laravel (eloquent) provides a fluent way to update related models.
Assuming the following model structure:
Rating.php
public function user()
{
return $this->belongsTo('App\User');
}
User.php
public function ratings()
{
return $this->hasMany('App\Rating');
}
You can easily update the relation via associate()
$user = User::findOrFail($userId);
$rating = Rating::findOrFail($ratingId);
$rating->user()->associate($user)->save();
Read more about Relationships in Eloquent
I have three models: User, Category, Announcement.
User model:
public function categories()
{
return $this->belongsToMany("App\Category");
}
public function announcements()
{
return $this->hasManyThrough('App\Announcement', 'App\Category');
}
Category model:
public function announcements()
{
return $this->belongsToMany('App\Announcement');
}
Announcement model:
public function categories()
{
return $this->belongsToMany('App\Category');
}
I need to select all announcements through user_categories table.
For this I do:
$res = User::where("id", 1)->with("announcements")->get();
dd($res);
In result I get SQL error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'announcements.category_id' in 'on clause' (SQL: select `announcements`.*, `categories`.`user_id` from `announcements` inner join `categories` on `categories`.`id` = `announcements`.`category_id` where `categories`.`user_id` in (1) and `announcements`.`deleted_at` is null)
Why Laravel does try to search ``announcements.category_id` in table?
In conclusion I need to get all announcements on categories which user subscribed.
Table Database structure:
Users
id | name
Announcements
id | name
categories
category_id | announcement_id
users_categories
category_id | user_id
So, I need to get all announcements through table users_categories where there are relation this table with categories that is belong to announcement table.
You cannot eager load this relationship because
To perform this query, Eloquent inspects the foreign key on the intermediate table.
Thus the error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'announcements.category_id'
Because HasManyThrough() looks for the relationship in the specified model table.
I would suggest you look at this thread:
https://laravel.io/forum/05-21-2014-problem-with-eloquents-hasmanythroughs-query
They show you how to write your own query to do that. An example would be, in the user model do
public function getAnnouncements() {
$announcements = [];
foreach( $this->categories as $category ) {
foreach( $category->announcements as $annoucement ) {
if ( !isset($announcements[$annoucement->id]) ) { //avoid duplicates
$annoucements[$announcement->id] = $announcement;
}
}
}
}
The nested foreach will give all announcement belonging to a category that related to a user.
Improving the function
public function getAnnouncements() {
$announcements = new Collection();
foreach( $this->categories as $category ) {
$announcements->collect($category->announcements);
}
}
I have two tables,
table users:
id, name, etc
table videos:
id, user_id, etc
Model: Video
public function user()
{
return $this->belongsTo('App\Models\User');
}
I want to select all videos where it is owned by the user "Max".
I have tried thing like the following:
$Videos = \App\Models\Video::with('user')->where('user.name','=','Max')->get();
Unknown column 'user.name' in 'where clause' (SQL: select * from `videos` where `videos`.`deleted_at` is null and `user`.`name` = Max)
Thanks!
That's what whereHas is for:
$Videos = \App\Models\Video::with('user')->whereHas('user', function($q){
$q->where('name','=','Max');
})->get();