【问题标题】:Laravel 5 conditional many to many sync()Laravel 5 条件多对多同步()
【发布时间】:2016-01-14 11:27:00
【问题描述】:

我有一个包含多对多类别和标签的内容模型。 类别和标签存储在同一个表中,带有布尔 tag 标志:

category_id | name        | tag
1           | Products    | 0
2           | bestsellers | 1

我的内容模型具有如此定义的条件关系:

public function categories() {
    return $this->belongsToMany('Foothing\Content\Z\Entities\Category\Eloquent\Category', 'content_content_categories', 'cid', 'tid')->where('tag', false);
}

public function tags() {
    return $this->belongsToMany('Foothing\Content\Z\Entities\Category\Eloquent\Category', 'content_content_categories', 'cid', 'tid')->where('tag', true);
}

虽然tag 标志在读取操作上正常工作,即

$categories = Content::find(1)->categories;
$tags= Content::find(1)->tags;

它在sync 操作中没有按预期工作,实际上是以下代码

$content->categories()->sync(1, 2, 3);

将同步整个表格,无论tag 标志如何:标签将被销毁,我的内容将仅与类别 1、2、3 相关。

这种方法有什么不好的地方吗?

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    我也遇到过和你一样的情况,我玩的就是这样

    // the 1st sync will remove all the relationship to the category table
    $content->categories()->sync([1, 2, 3]);
    // the 2nd sync is to extends the relationship from the 1st
    $content->tags()->syncWithoutDetaching([4, 5, 6]);
    

    两者都来自同一张表,这意味着id 应该不同。这应该可以很好地解决问题

    【讨论】:

      【解决方案2】:

      当您调用Content::find(1)->categories 或任何其他关系时,它会通过Illuminate/Database/Eloquent/Model.php 文件line 2732 调用,其中此方法getRelationshipFromMethod 从模型中调用& 例如,这将返回return $this->belongsToMany('Foothing\Content\Z\Entities\Category\Eloquent\Category', 'content_content_categories', 'cid', 'tid')->where('tag', false); 然后它调用getResults on返回并收集数据。

      另一方面,当您调用 $content->categories() 时,这是从您的 Content 模型类直接访问的方法,并且作为回报,它返回 Illuminate\Database\Eloquent\Relations\BelongsToMany 类实例。

      所以要实现你的目的

      $content->categories()->where('content_content_categories.tag', false)
              ->sync([1, 2, 3]);//for syncing categories
      
      $content->tags()->where('content_content_categories.tag', true)
              ->sync([1, 2, 3]);//for syncing tags
      

      另外不要忘记同步方法接受 id 数组或集合检查这里https://github.com/laravel/framework/blob/22c06c504067cc52787f9fc4b04de4e496442212/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php#L756

      【讨论】:

      • 这似乎行不通,伙计,当我执行同步()时,将执行此删除查询:delete from content_content_categories` 其中cid = ?和tid (?, ?, ?)`。如您所见,没有证据表明标准中使用了标记字段。
      • 我认为在不更改数据库结构的情况下使用 sync() 根本不可能,因为查询中涉及的唯一表是数据透视表,它没有标签列信息。
      猜你喜欢
      • 1970-01-01
      • 2015-02-14
      • 2021-07-22
      • 2021-01-13
      • 2021-12-21
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多