【问题标题】:Laravel - sync with extra columnLaravel - 与额外的列同步
【发布时间】: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 得到select type_id` where table_id = '1';` Laravel 的哪个版本?也许这是 L5 中 Eloquent 的一个错误(我还没有使用当前提交)?
  • 可能是L5的问题。我只做了4.2的测试。
  • @Bogdan 感谢您的检查。我今天在 L5 决赛中对其进行了测试,现在它工作正常。这可能是一个错误。

标签: php laravel laravel-4 eloquent laravel-5


【解决方案1】:

你应该使用 Eloquents 多态关系 (http://laravel.com/docs/4.2/eloquent#relationships)

class Category extends Eloquent {

    public function categorizable()
    {
        return $this->morphTo();
    }

}

class Person extends Eloquent {

    public function categories()
    {
        return $this->morphMany('Category', 'categorizable');
    }

}

现在我们可以从 person 中检索类别:

$person = Person::find(1);

foreach ($person->categories as $category)
{
    //
}

并从类别访问个人或其他所有者:

$category = Category::find(1);

$categorizable_model = $category->categorizable; //e.g. Person

【讨论】:

    【解决方案2】:

    我可以确认这是我使用的 Laravel 5 提交中的一个错误。我已经升级到 Laravel 5 最终版本,现在查询已经生成。

    【讨论】:

      猜你喜欢
      • 2015-05-08
      • 2015-12-24
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      • 2018-07-19
      • 2020-11-10
      • 2023-03-26
      • 2015-05-07
      相关资源
      最近更新 更多