Laravel 5 条件多对多同步()

bra*_*orf 5 php laravel eloquent laravel-5

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

category_id | name        | tag
1           | Products    | 0
2           | bestsellers | 1
Run Code Online (Sandbox Code Playgroud)

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

$categories = Content::find(1)->categories;
$tags= Content::find(1)->tags;
Run Code Online (Sandbox Code Playgroud)

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

$content->categories()->sync(1, 2, 3);
Run Code Online (Sandbox Code Playgroud)

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

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

ARI*_*ANA 0

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

另一方面,当您调用$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
Run Code Online (Sandbox Code Playgroud)

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