Как получить множественный атрибут (массив) товара (массива) на странице товара в Laravel? - PullRequest
0 голосов
/ 26 апреля 2020

Я вроде как нуб, так что прости меня, если ты думаешь, что вопрос рудиментарный.

 $product = Products::where('product_slug', $slug)->first();  
 // the products page where products are displayed by using @foreach and @endforeach

 $product_attributes = ProductAttribute::all()->where('SKU_code', $product->SKU_code);  
 //this control the attributes of each product like price, 

Как отобразить как товар, так и атрибут, показывая доступные размеры каждого товара в том же foreach l oop?

1 Ответ

0 голосов
/ 26 апреля 2020

Сначала вы должны определить отношение в Product модели:

function product_attributes() {
    return $this-hasMany(ProductAttribute::class); // assuming that product_attributes table has product_id column in it.
}

В контроллере получите продукты со всеми атрибутами:

// with product_attributes (name of the relation)
$products = Product::where('product_slug',$slug)->with('product_attributes')->get();

Вы можете отфильтровать, какие атрибуты включить из вашего отношение, например,

$products = Product::where('product_slug',$slug)->with(['product_attributes'=>function($query) {
    $query->where('attribute_name','product_size');
])->get();

позже, в блейде:

@foreach($products as $product)  
    {{$product->name}}
    // don't use product_attributes() because it will make a query for each product! 
    // use it without parthanees
    @foreach($product->product_attributes as $attribute) 
        {{$attribute->name}}:  {{$attribute->value}}
    @endforeach
@endforeach

Проверьте Официальная документация для получения дополнительной информации об отношениях и способах их запроса.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...