简体   繁体   中英

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.

$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

I want the result : 1 item with its first image. 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.

You have to tackle this problem in three steps:

Step 1: Find the id's of first image for each item

$minQuery  = DB::table('item_images')
    ->select(DB::raw('min(id) AS id'))
    ->groupBy('item_id')
    ->toSql();

Step 2: Retrieve details of those images

$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

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM