简体   繁体   中英

Laravel - Set collection data from another collection

I have two tables: products and colors .

Products

id | product_name | color_id
----------------------------
1  | Product 1    | 1
2  | Product 2    | 2

Colors

id | name
---------
1 | blue
2 | silver
3 | green

And i have collection:

$product = Product::all();

And i want to have another collection from color table with colors which exists in product collection. So i want to see colors: blue (product 1) and silver (product 2) without green. Is it possible to get something like this? I think about relationship but i'm not sure how to do it. Thanks.

If you want take colors from colors table that are assigned to any product, then you can do like this:

$products = Product::all();
$assigned_color_ids = $products->pluck('id')->toArray();
$colors = Color::whereIn('id', $assigned_color_ids)->get();

For your given table, the query will be whereIn('id', [1, 2]) because color with id 3 is not used in products table

maybe can try this, in your COlors model define a relation to products

/**
 * Get the products for the color.
 */
public function products()
{
    return $this->hasMany('App\Products','color_id');
}

and you can access to all products from color model,

$colorswithproducts = Colors::whereHas('products')->get();

dd($colorswithproducts);

1 => [
    'name' => 'blue'
    'products' =>
    [
        "id" : "1",
        'name' => ....
    ] 
 ]

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