[英]Join table one to many relationship only 1 row from second table
I have Items and Images tables with one to many relationship. 我有一对多关系的项目和图像表。
1 item can have many images, but i need only 1 image to join the table. 1个项目可以有很多图像,但我只需要1个图像来加入表格。
$items = DB::table('items')
->leftjoin('item_images', function($join){
$join->on('item_images.item_id','=','items.id');
})
->select('items.id', 'items.name', 'item_images.image_file')
->get()
this will return all images, but I want only first image. 这将返回所有图像,但我只想要第一张图像。 first() is not working, limit(1) is not working
first()不起作用,limit(1)不起作用
I want the result : 1 item with its first image. 我想要结果:1个项目及其第一个图像。 how to achive this?
如何实现这一目标?
Try this 尝试这个
$items = DB::table('items')
->leftjoin('item_images','items.id','=','item_images.item_id')
->select('items.id', 'items.name', 'item_images.image_file')
->distinct()
->get();
You can use join, but its better to us eloquent relationship. 你可以使用join,但它对我们更有说服力的关系。
You have to tackle this problem in three steps: 您必须分三个步骤解决此问题:
Step 1: Find the id's of first image for each item 第1步:找到每个项目的第一张图片的ID
$minQuery = DB::table('item_images')
->select(DB::raw('min(id) AS id'))
->groupBy('item_id')
->toSql();
Step 2: Retrieve details of those images 第2步:检索这些图像的详细信息
$joinQuery = DB::table('item_images')
->select('item_images.id', 'item_images.item_id', 'item_images.image_file')
->join(DB::raw("($minQuery) AS m"), 'item_images.id', '=', 'm.id')
->toSql();
Step 3: Join it with items
table 第3步:使用
items
表连接它
$items = DB::table('items')
->select('items.id', 'items.name', 'ii.image_file')
->leftJoin(DB::raw("($joinQuery) AS ii"), 'items.id', '=', 'ii.item_id')
->get();
I haven't tested this on a machine 我没有在机器上测试过这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.