Вы должны определить отношения в ваших Product
и Feature
Модель
class Product extends Model {
public function features(){
return $this->belongsTo(Feature::class);
}
}
class Feature extends Model {
public function products(){
return $this->hasMany(Product::class);
}
}
Я предполагаю, что каждый Product
имеет атрибут feature_id
, который содержит идентификатор Feature
, к которому он принадлежит.
$products = Product::with([’features’])->where(category_id, $category_id)->get(); // This query will return list of product
foreach($products as $product){
// You can access $feature of product like this
$feature = $product->feature;
}
Поскольку я уже определил обратную связь между обеими моделями, я также могу получить доступ к продукту из функции.
$feature->products(); // This will return a collection of Product and I can perform any sort of query on that too
// Like count number of Products
$feature->products()->count();
$feature->products()->first(); // get the first product
$feature->products()->last(); // get the last product
И так далее, и так далее.