[英]Should i separate Pivot tables for each feature in laravel?
I'm building review product application where there are 3 database tables - Review - Categories - Affiliates我正在构建评论产品应用程序,其中有 3 个数据库表 - 评论 - 类别 - 附属公司
At first i created a pivot table with 2 entries review_id & category_id & the sync was successfull.起初,我创建了一个 pivot 表,其中包含 2 个条目 review_id 和 category_id 并且同步成功。 Later i added another column "affiliate_id" to the pivot table & the sync was successfull but with multiple entries.
后来我在 pivot 表中添加了另一列“affiliate_id”,同步成功但有多个条目。 Let me explain
让我解释
Here's my controller for review -这是我的 controller 供审查 -
$result->affiliates()->sync($aff_ids);
$result->category()->sync($product);
The above code is creating sperate pivot entries -上面的代码正在创建单独的 pivot 条目 -
Pivot Table - Pivot 表 -
+-----------+-------------+--------------+
| review_Id | category_id | affiliate_Id |
+-----------+-------------+--------------+
| 1 | null | 1 |
| 1 | 1 | null |
+-----------+-------------+--------------+
Is the above pivot table correct or should i create seperate pivot tables for affiliates & categories?上面的 pivot 表是否正确,或者我应该为附属机构和类别创建单独的 pivot 表?
If the pivot table is not correct & if there is no need for seperate pivot tables then what i want to achieve is -如果 pivot 表不正确并且不需要单独的 pivot 表,那么我想要实现的是 -
+-----------+-------------+--------------+
| review_Id | category_id | affiliate_Id |
+-----------+-------------+--------------+
| 1 | 1 | 1 |
+-----------+-------------+--------------+
The affiliate_id column can have have multiple entries so final result i want is - affiliate_id 列可以有多个条目,所以我想要的最终结果是 -
+-----------+-------------+--------------+
| review_Id | category_id | affiliate_Id |
+-----------+-------------+--------------+
| 1 | 1 | 1 |
| 1 | 1 | 2 |
| 1 | 1 | 3 |
+-----------+-------------+--------------+
use withPivot;与枢轴一起使用;
in Review Model class审查中 Model class
public function category()
{
return $this->belongsToMany(Category::class)->withPivot('affiliate_id');
}
Then然后
foreach ($categories as $category) {
$category_id_array[$category->id] = ['affiliate_id' => $affiliate->id];
}
//Insert into offence_photo table
$review->category()->sync($category_id_array, false);//dont delete old entries= false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.