Laravel“BelongsToMany”关系始终在其“更新”键中返回值(即使记录没有更改)

问题描述 投票:0回答:1

我在

project_media
tag
数据透视表
project_media_tag
之间有多对多关系。 它有附加字段
qty

我正在执行

syncWithoutDetaching
来附加任何新的/更新现有的记录 (其附加字段)。但它给了

Array
(
    [syncResult] => Array
        (
            [attached] => Array
                (
                )

            [detached] => Array
                (
                )

            [updated] => Array 
                (
                    [0] => 92 // tag_id
                    [1] => 93
                )

        )
)

即使我的数据透视中有这些标签(92,93),附加字段中的值完全相同

qty


问题:我的印象是,如果我的数据透视表中的任何内容发生更改(例如
updated
),它应该只返回
qty
键中的值,应该吗?

class ProjectMedia extends Model
{

    public function syncTags(){

        // ...
        $projectMedia = self::firstOrNew(['id' => $item['id']],$update);
        
        // ...

        $projectMedia->save(); // Creating & Updating Both

        $syncResult = $projectMedia->btm_Tags()->syncWithoutDetaching($requestedPmTags);
        
        // ... output $syncResult
    }


    // Relationship
    public function btm_Tags()
    {
        return $this->belongsToMany("App\Models\Tag",'project_media_tag','target_id',
                                    'tag_id','id','id')->withPivot('qty')
            ->withTimestamps()->using('App\Models\ProjectMediaTag');
    }
}

架构

项目媒体

id 项目_id 目标ID 目标类型 路径 注意 创建于 更新于 已删除_at 媒体类型 ref_id
1

项目媒体标签

目标ID 目标类型 标签_id 数量 创建于 更新于 已删除_at

标签

id 公司_id ref_id 参考类型 名字 订购依据 创建于 更新于 已删除_at 目标ID
laravel-5 eloquent eloquent-relationship
1个回答
0
投票

此特定问题最接近的解决方案是here

它说你必须删除

withTimestamps()
,删除它确实可以解决问题。

仅当

qty
的值更改时,
updated
键会返回值(与 tag_id 相关的模型 ID),指示值已更改。但是,这并不完全是我想要的,因为我需要这些时间戳

© www.soinside.com 2019 - 2024. All rights reserved.