Laravel sort by pivot table column - laravel

I am trying to sort an eloquent query in laravel by a column from the pivot table.
Basically as long as the product is favorited by the user, it is added to the pivot table, and it should first show the favorited ones, and then the remaining ones. Since I will be using foreach in the blade.
products table contains these columns:
id, category, product_name, priority, status, created_at, updated_at
users table contains these columns:
id, name, email, created_at, updated_at
with the following in the users model:
public function favorites()
{
return $this->belongsToMany(Products::class, 'favorites', 'user_id', 'product_id')
->withTimeStamps();
}
favorites table contains these columns:
id, user_id, product_id, created_at, updated_at
In the controller, the eloquent query is currently:
$productinprogress = Products::all()
->sortByDesc("priority")
->where('status', 'inprogress');
I am just confused as to how to tackle this.
Your help is appreciated. Thank you so much.

I think you should make two queries to avoid loading duplicate products, first one for favorite products, second one should be some thing like this:
Products::all()->sortByDesc("priority")->where('status', 'inprogress')->whereNotIn('id', $favorite_products);
and then in the blade file, you make two foreach, first one for favorites, and 2end for others.

you can use something like bellow:
$productinprogress = Products::all()
->where('status', 'inprogress')
->sortByDesc("priority");
and if you want an efficient solution using eager loading and loading favorites too, use following code
$productinprogress = Products::all()
->with('favorites')
->where('status', 'inprogress')
->sortByDesc("priority");

Related

How to access multiple model data from an eloquent call

I currently have a product table with the following columns:
id, product_name, product_type, description
I also have three more tables:
medias, attributes, coatings
each of those tables has an id, name, description, img
Each product created din the product table will have multiple, medias, attributes and coatings. To address this I created a table product_relations which contains the columns:
id, product_id, media_id, attribute_id, coating_id
From here I thought I would make a call to product_relations with the product_id and then pull each record so I can access the data. However I'm stuck on how I would do this as an eloquent relationship. Would I do separate has many's in my Product_Relation model like so:
public function media()
{
return $this->hasMany('App\Media');
}
public function attributes()
{
return $this->hasMany('App\Attributes');
}
etc? Or is there a simpler way to build this to access all that at once?

Laravel HasManyThrough CrossDatabaseRelation

strange question:
I have 3 Models
Order
with id as PK
Orderline
with id as PK and order_id as FK. brand and partnumber are two separatet colums
Article
with combined PK brand and partnumber
**which is on another database **
One Order hasMany Orderlines. Every Orderline hasOneArticle.
i had make a function within order:
public function articles()
{
$foreignKeys = [
'brand_id',
'article_number',
];
$localKeys = [
'brand',
'partnumber',
];
return $this->hasManyThrough('App\Models\Masterdata\Articles','App\Models\Oms\OrderLine',$foreignKeys,$localKeys,'id','id');
}
How can i retrieve all Attributes from articles through Order?
I tried something like this:
$order = Order::find($orderid)->articles();
dd($order);
//did not work
$order = Order::with('orderlines.articles')->where('id','=',$orderid)->get();
Do you have an idea for me?
You can configure more than one database in the database.php config, and specify the $connection name in the Model class.
For the most part, Eloquent doesn't do JOINs, it just does IN statements on the key values from the preceding query, and programmatically marries the results together after the fact. Partly to avoid the mess of keeping table aliases unique, and partly to offer this kind of support- that your relations don't need to live in the same database.
In other words, what you have there should work just fine. If there's a specific error getting thrown back though, please add it to your post.

How do you combine the following three tables with eloquent in laravel?

How to combine 3 Many to Many tables with eloquent in the laravel
Hi Friends, please help me,
How do you combine the following three tables with eloquent in laravel?
The following table structure and figures:
(https://i.stack.imgur.com/BfISA.jpg)
Member table structure
{member_id: primary key, name, created_at, updated_at}
List table structure
{list_id: primary key, member_id: foregn key, price_id: foreign key, created_at, updated_at}
Price table structure
{price_id: primary key, name_price, created_at, updated_at}
Can you give me sample source code for view.blade, controller and model.
Thank you, your answer is very meaningful
in your member model add relationship function list(). Then in your list model add relationship function price then use below code
app\Member.php
public function list(){
return $this->hasMany('App\List', 'member_id');
}
app\List.php
public function price(){
return $this->hasMany('App\Price', 'price_id');
}
in your controller
$result = Member::with(['list.price'])->get();
it will give you a member list with list and price table data.

eloquent filter result based on foreign table attribute

I'm using laravel and eloquent.
Actually I have problems filtering results from a table based on conditions on another table's attributes.
I have 3 tables:
venue
city
here are the relationships:
a city has many locations and a location belongs to a city.
a location belongs to a venue and a venue has one location.
I have a city_id attribute on locations table, which you may figured out from relationships.
The question is simple:
how can I get those venues which belong to a specific city?
the eloquent query I expect looks like this:
$venues=Venue::with('location')->where('location.city_id',$city->getKey());
Of course that's not gonna work, but seems like this is common task and there would be an eloquent command for it.
Thanks!
A couple of options:
$venues = Venue::whereIn('location_id', Location::whereCityId($city->id)->get->lists('id'))
->get();
Or possibly using whereHas:
$venues = Venue::whereHas('location', function($query) use ($city) {
$query->whereCityId($city->id);
})->get();
It is important to remember that each eloquent query returns a collection, and hence you can use "collection methods" on the result. So as said in other answers, you need a Eager Loading which you ask for the attribute you want to sort on from another table based on your relationship and then on the result, which is a collection, you either use "sortBy" or "sortByDesc" methods.
You can look at an example below:
class Post extends Model {
// imagine timpestamp table: id, publish, delete,
// timestampable_id, timestampble_type
public function timestamp()
{
return $this->morphOne(Timestamp::class, 'timestampable');
}
}
and then in the view side of the stuff:
$posts = App\Post::with('timestamp')->get(); // we make Eager Loading
$posts = $posts->sortByDesc('timestamp.publish');
return view('blog.index', compact('posts'));

Eloquent - Two Relationships In One?

I've been getting along slowly but surely with Laravel / Eloquent, but am now stumped:
entries Table:
id
user_id
group_id
content
users Table
id
faculty_id
name
group Table:
id
name
faculty Table
id
name
So entries are related to users and groups, and users are related to faculties - I've set up the basic relationships without a problem, and this enables me to find all entries by users from a certain faculty:
Faculty Model:
public function entries()
{
return $this->hasManyThrough('Entry','User');
}
Controller:
Faculty::find(Faculty-ID-here)->entries;
However, I now need to find entries by users that are from a certain faculty AND from a certain group, and I don't know how to write this combination this in Eloquent.
Hope that makes sense! Any suggestions?
Something like:
Entries::whereHas('user', function($q) {
$q->where('faculty_id', $facultyID);
})
->where('group_id', $groupID)
->get();
Assuming you have set up your 'user' relationship.

Resources