laravel - laravel 与自定义查询的多对多关系
问题描述
我有两个具有多对多关系的表产品和道具。每个产品都有一些道具,每个道具都适用于某些产品。在搜索过滤器中,我只需要获取具有选定道具的产品。我怎样才能做到这一点?
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
....
$table->timestamps();
});
Schema::create('props', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
....
$table->timestamps();
});
Schema::create('product_prop', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('product_id');
$table->unsignedBigInteger('prop_id');
$table->timestamps();
$table->foreign('product_id')
->references('id')
->on('products')
->onDelete('cascade');
$table->foreign('prop_id')
->references('id')
->on('props')
->onDelete('cascade');
});
products:
id=> 1, title=> p1
id=> 2, title=> p2
id=> 3, title=> p3
id=> 4, title=> p4
id=> 5, title=> p5
props:
id=> 1, title=> p1
id=> 2, title=> p2
id=> 3, title=> p3
id=> 4, title=> p4
id=> 5, title=> p5
product 1 has prop 1 and 2
product 3 has prop 2 and 4
product 4 has prop 5
$selectedProps = [1,5]
所以我需要得到产品1和4!但我不知道如何获得。
解决方案
试试下面的代码,在此之前我假设你有Products
模型和Props
模型。
在你的Product
模型中
public function props(){
return $this->hasMany('Props');
}
在你的Props
模型中
public function product(){
return $this->belongsToMany('Product');
}
现在构建器获取所选道具的产品。
Props::with('product')->whereHas('product')->where('id', $selectedPropsId)->get();
注意:我的回答是基于您的问题,抱歉,您的问题没有更多信息。
推荐阅读
- cron - 可以将 cron 作业设置为每小时 5 分钟后运行吗?
- php - 使用蒸汽冷凝器库未找到“SourceServer”类
- reactjs - 单击选择字段中的渲染项目?
- servicestack - OrmLite 不允许在 postgresql 查询中使用 '@@'
- javascript - ONAFTERPRINT 事件在错误的按钮上触发
- javascript - 使用 Internet Explorer 时始终显示更新通知
- regex - bash 正则表达式替换 html 文件中的 index.css
- python - 有没有办法用 Pillow/Python 压缩/优化 jpg2000 图像?
- core-data - 为关系内部的属性设置值时“无法在 NSManagedObject 类上调用指定的初始化程序”(核心数据)
- json - swift中创建json对象:一行中的连续语句必须用';'分隔