【发布时间】:2020-07-19 12:21:50
【问题描述】:
我有 3 个模型 店铺模型、产品模型、图片模型
我想检索包含最近 3 个产品型号及其图片的商店集合,并根据最新产品对我的集合进行排序。
我在 laravel 6 中尝试了 leftjoint 和 joint 以便能够对结果进行排序,但我得到了所有商店的产品(我只需要每个商店的最后 3 个产品),
当我使用关节时,我无法检索产品图片
我也在 laravel 中尝试过“with”方法,我无法根据product.creatred_at 对结果进行排序,而且我也用这种方法获得了所有相关产品。(正如我提到的,我需要最后 3 个产品)
class Shop extends Model
{
public function products()
{
return $this->hasMany('App\Product');
}
}
class Product extends Model
{
public function shop()
{
return $this->belongsTo('App\Shop');
}
public function pictures()
{
return $this->morphMany('App\hPicture', 'pictureable');
}
}
Shop::select('shops.*', 'products.id', 'products.shop_id', 'products.name as pname', 'products.user_id', 'products.code', 'products.price')
->with(['pictures', 'products.pictures'])
->leftjoin('products', function ($leftJoin) {
$leftJoin->on('shops.id', '=', 'products.shop_id');
});
$dataList = $dataList->orderBy($field, $order);
$dataList = $dataList->paginate(5)->appends(['sortField' => $field, 'sortOrder' => $order]);
产品和店铺模型的表格布局为:
Schema::create('shops', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug');
$table->string('phone')->nullable();
$table->string('address')->nullable();
$table->timestamps();
$table->string('description')->nullable();
$table->uuid('uuid');
});
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('shop_id')->unsigned();
$table->foreign('shop_id')->references('id')->on('shops');
$table->string('name');
$table->string('code');
$table->string('slug');
$table->integer('price');
$table->uuid('uuid');
$table->timestamps();
});
【问题讨论】:
标签: laravel relationship laravel-6