简体   繁体   中英

Laravel: Select Distinct on one to many relationship

So i have this relationship between my two Models

Product.php

public function photos()
{
    return $this->hasMany('App\Photo');
}

Photo.php

public function product()
{
    return $this->belongsTo('App\Product');
}

What I want to do is to get only one photo for each product. this is my query

$my_ads = DB::table('products as p')
                    ->join('photos as pic','p.id','=','pic.product_id')
                    ->select(DB::RAW('DISTINCT(pic.product_id)'),'p.*','pic.file_path')
                    ->get();

The result I am getting in this query is repeating. If my first product has five photos, the collection will have 5 instances of the same product with different photos.

How can I achieve that for every product I can only have one photo? Thank you very much

Why are you not doing this the Eloquent way?

App\Product::with('photos')->get();

This will retrieve all your products, with their photos and no product will be repeated.

In eloquent, you can do it easily.

Product::with([
    'photos' => function($q){
        $q->take(1);
    }
])->get();

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