我有4个模型与指定用途。
- 商家
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Merchant extends Model
{
use HasFactory;
use SoftDeletes;
protected $fillable = [
'name',
'address',
'pinpoint',
'latitude',
'longitude',
'open_hour',
'close_hour',
'tax_restaurant',
'tax_service',
];
protected $hidden = [
'deleted_at',
'created_at',
'updated_at',
];
public function produk()
{
return $this->belongsToMany(Produk::class, 'merchant_produks');
}
}
- 普罗杜克
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Produk extends Model
{
use HasFactory;
use SoftDeletes;
protected $fillable = [
'kategori_id',
'name',
'combo',
'price',
'description',
'option',
'picture',
];
protected $hidden = [
'deleted_at',
'created_at',
'updated_at',
];
public function kategori()
{
return $this->belongsTo(Kategori::class);
}
public function merchant()
{
return $this->belongsToMany(Merchant::class, 'merchant_produks');
}
}
- Merchant_produk(作为Merchant和Produk的枢纽)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class MerchantProduk extends Model
{
use HasFactory;
protected $fillable = [
'produk_id',
'merchant_id',
];
protected $hidden = [
'created_at',
'updated_at',
];
}
- 卡捷戈里
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Kategori extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
protected $hidden = [
'created_at',
'updated_at',
];
public function produk()
{
return $this->hasMany(Produk::class);
}
}
- 控制器的功能
public function selectedmerchant($kategoriID, $merchantID)
{
// $data = Merchant::with([
// 'produk' => function ($query) use ($kategoriID) {
// $query->wherePivot('kategori_id', $kategoriID);
// }
// ])->where('id', $merchantID)
// ->get();
// $data = Produk::with(['merchant' => function ($query) use ($merchantID) {
// $query->wherePivot('merchant_id', $merchantID);
// }])->where('kategori_id', $kategoriID)->get();
$data = Merchant::with('produk')->where('id', $merchantID)->get();
return JsonFormater::buildResponse(200, 'success', $data);
// return JsonFormater::buildResponse(200, 'success', [
// 'kategori' => $kategoriID,
// 'merchant' => $merchantID,
// ]);
}
我想做的是用2个参数过滤数据,即KategoriID和MerchantID。
我已经尝试使用wherePivot,但是,我意识到它不能通过类别ID过滤数据。
这是函数的临时结果:
1条答案
按热度按时间xwbd5t1u1#
在商家模型中创建类别关系,如hasManyThrough2LinkTables。然后你可以在关系中使用where。How to create Laravel 8 custom relation HasManyThrough 2 and 3 Link Tables so involving 4 or 5 tables in total?