【发布时间】:2018-07-26 17:59:41
【问题描述】:
我有一个复杂的关系,例如 Category 和 Products 之间的多对多关系,Product 可以有来自不同商店(用户)的许多 Inventory 列表。 Shop 可以有多个相同 Product 的列表作为变体(颜色/大小)。
到目前为止一切都很好!
问题从向访问者显示列表时开始。我想显示一个类别下的所有列表,但不想显示同一商店的同一产品的多个列表。相反,想从商店中挑选最低的sale_price 列表。
我有三个模型,关系如下:
class Category extends Model
{
public function products()
{
return $this->belongsToMany(Product::class);
}
}
class Product extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
public function inventories()
{
return $this->hasMany(Inventory::class);
}
}
class Inventory extends Model
{
public function product()
{
return $this->belongsTo(Product::class);
}
}
表格:
//Categories
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
});
//Products
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
});
//Pivot table
Schema::create('category_product', function (Blueprint $table) {
$table->integer('category_id');
$table->integer('product_id');
});
//Inventories
Schema::create('inventories', function (Blueprint $table) {
$table->increments('id');
$table->integer('shop_id');
$table->integer('product_id');
$table->string('sku', 200);
$table->string('title');
$table->decimal('sale_price', 10, 2);
});
由于 Laravel 不提供任何 manyToManyThough() 关系。我在Category 模型中添加了listings 方法。此方法返回所有列表:
public function listings()
{
$product_ids = $this->products()->pluck('products.id')->all();
return Inventory::whereIn('product_id', $product_ids)->paginate(20);
}
然后我尝试了这个:
public function listings()
{
$product_ids = $this->products()->pluck('products.id')->all();
return Inventory::whereIn('product_id', $product_ids)->groupBy('shop_id','product_id')->paginate(20);
}
这些方法产生 MySQL GroupBy 错误。是的,我可以在获取所有结果后过滤结果,但这会影响分页。如何获得排序结果并保持分页能力。谢谢,一天比一天,我对社区越来越感激。 :)
【问题讨论】:
标签: mysql laravel eloquent many-to-many laravel-5.5