【发布时间】:2015-01-31 12:07:04
【问题描述】:
我有 3 张桌子
类型
type_id
人
person_id
类别
category_id
table_name
table_id
person_id
在类别中,我有不同的表/模型与 Type 模型的连接,所以如果我想将 type_id 与 person_id = 23 的人连接起来,查询应该如下所示:
SELECT * FROM category WHERE table_name='person' AND table_id = 23
在我的 Person 模型中,我以这种方式定义了与 Type 的关系:
public function groups()
{
return $this->belongsToMany('Type', 'category',
'table_id', 'type_id')->wherePivot( 'table_name', '=', 'person' );
}
当我想获得这些类型并使用时:
$person->groups()->get()
查询如下所示:
select `type`.*, `category`.`table_id` as `pivot_table_id`, `category`.`type_id` as `pivot_type_id` from `type` inner join `category` on `type`.`type_id` = `category`.`type_id` where `category`.`table_id` = '23' and `category`.`table_name` = 'person';
看来是对的。
但我想使用 sync() 将类型与人员同步,这就是问题所在。
当我使用时:
$person->groups()->sync('1' => ['table_name' => 'person']);
我看到从类别中获取所有记录以用于sync 的查询如下所示:
select `type_id` from `category` where `table_id` = '23';
所以它不使用
`category`.`table_name` = 'person'
条件,因此同步将无法按预期工作。
有什么简单的方法可以解决还是要手动同步?
【问题讨论】:
-
我刚刚做了一个快速测试,复制了你发布的模型,这个
Person::find(1)->groups()->sync(['1' => ['table_name' => 'person']])生成了这个SELECT type_id FROM category WHERE table_name = "person" AND table_id = 1。所以它似乎按预期工作。 -
@Bogdan 你确定吗?我刚刚使用了
Person::find(1)->groups()->sync(['1' => ['table_name' => 'person']]);,我从category得到selecttype_id` wheretable_id= '1';` Laravel 的哪个版本?也许这是 L5 中 Eloquent 的一个错误(我还没有使用当前提交)? -
可能是L5的问题。我只做了4.2的测试。
-
@Bogdan 感谢您的检查。我今天在 L5 决赛中对其进行了测试,现在它工作正常。这可能是一个错误。
标签: php laravel laravel-4 eloquent laravel-5