我有下一个数据库结构 - 产品可以在很多类别,产品可以在许多市场。模特\App\Product
,\App\Market
和\App\Category
创造了许多关系 - belongsToMany()
。
class Product extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category');
}
public function markets()
{
return $this->belongsToMany('App\Market');
}
}
class Category extends Model
{
public function products()
{
return $this->belongsToMany('App\Product');
}
}
class Market extends Model
{
public function products()
{
return $this->belongsToMany('App\Product');
}
}
在route.web
,我得到了展示产品的类别
Route::get('/catalog/{current_category?}', 'CatalogController@index')->name('catalog.index');
我可以从会话中获得当前市场(打开网站时用户选择市场)
$market = $request->session()->get('market'); // or Session::get('market');
// $market->id
// $market->slug
在我的MarketController@index
中,我希望从路线和当前市场中获得所有类别的产品。但是我怎么能这样做呢?我可以获得类别产品和市场产品。但我怎样才能同时获得类别和市场产品?
public function index(Request $request, Category $current_category = null)
{
if ($current_category) {
$market_id = $request->session()->get('market')->id;
$products = $current_category->products;
// ...
}
}
如果您想要基于类别的产品,请使用以下查询:
$products = $current_category->products()->get();
如果您想要基于市场的产品,首先您需要获得市场对象,而不是基于它获得产品。
$market = Market::find($market_id);
$market_products = $market->products()->get();
如果您想要基于市场和类别的产品,您可以使用以下查询。
$products = Product::whereHas('categories', function($q) {
$q->where('category_id', $current_category->id);
})
->whereHas('markets', function($q) {
$q->where('market_id', $market_id);
})
->get();
正如评论中指出的那样,你可以通过多对多的多态关系实现它
categories
id - integer
name - string
markets
id - integer
name - string
products
id - integer
name - string
productables
product_id - integer
productable_id - integer
productable_type - string
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
/**
* Get all of the products for the category.
*/
public function products()
{
return $this->morphToMany('App\Product', 'productable');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Market extends Model
{
/**
* Get all of the products for the market.
*/
public function products()
{
return $this->morphToMany('App\Product', 'productable');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* Get all of the categories that are assigned this product.
*/
public function categories()
{
return $this->morphedByMany('App\Category', 'productable');
}
/**
* Get all of the markets that are assigned this product.
*/
public function markets()
{
return $this->morphedByMany('App\Market', 'productable');
}
}
您可以获得属于两者(特定类别和特定市场)的产品
$products = \App\Product::where(['productable_id' => $category->id, 'productable_type' => get_class($category)])->orWhere(['productable_id' => $market->id, 'productable_type' => get_class($market)])->get();
从您的问题中假设已经知道类别和市场。
@YasinPatel的解决方案也应该有效,但这样您的数据库架构更灵活。这取决于你。研究多态关系解决方案,你会发现它很有趣。