Query to get related models from DB facade I'm sure the answer to this is staring me in the face, but I can't figure it out.
I have a basic query to grab some products for the homepage:
$antiques = DB::table('antiques')->latest()->limit(20)->get();
So In my view I can get the antique title using
{{ $antique->title }}
which works fine, however, I need to get the associated images of those antiques, so I can use them in the homepage view. The image paths exist in another table images and are related to the antiques via the `antiques_id' field. Not sure on the query I should be using to get the related images.
You can add a join to your query
$antiques = DB::table('antiques')
->join('images', 'images.antiques_id', '=', 'antiques.id')
->latest()
->limit(20)
->get(['antiques.*', 'images.path']);
If the relation is one to many then you will also need to group by antiques.id and select the path with group_concat.
Any reason you aren't using eloquent models?
If you use models then your query gets very simple
Antiques::with('images')->latest()->limit(20)->get();
Thank you! That was indeed what i needed - I had a feeling it would be simple...
Please sign in or create an account to participate in this conversation.