Laravel中的OneToOne关系更新或创建操作updateOrCreate

3
在我的 Web 应用程序中,我有以下模型:
InstagramAccount.php 
UserPageFeed.php

每个Instagram账号都有一条记录进入UserPageFeed,每个UserPageFeed属于一个Instagram账号的记录,那么这是“一对一”的关系。
问题:
我的下面的代码不能更新表中的现有行并再次创建。
$userSelectedPage = InstagramAccount::whereUsername('my_page')->first();
$userPageFeeds = new UserPageFeed();
$userSelectedPage->account()->updateOrCreate([
    'instagram_account_id' => $userPageFeeds->id, //exsiting row
    'page_name' => 'test',
    'feeds' => 'test',
    'cache_time' => Carbon::now()->addHour(6),
]);

或者这段代码:
$userSelectedPage = InstagramAccount::whereUsername('content.world')->first();
$salam = $userSelectedPage->account()->updateOrCreate([
    'instagram_account_id' => $userSelectedPage->id,
    'page_name' => 'aaaaaaa',
    'feeds' => 'ddd',
    'cache_time' => Carbon::now()->addHour(6),
]);

用户页面动态表结构:

id                     ->Primary
instagram_account_id   ->Index
feeds
page_name
cache_time
created_at
updated_at 

使用这个索引:

"Keyname":user_page_feeds_instagram_account_id_foreign  "Column":instagram_account_id

instagram_accounts表结构:

id                     ->Primary
user_id                ->Index
uid
fid
proxy
avatar
username
password
checkpoint
account_data
people_data
status
created_at
updated_at 

InstagramAccount 模型:

class InstagramAccount extends Model
{
    protected $guarded = ['id'];

    protected $casts = [
        'account_data' => 'array',
        'people_data' => 'array'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function account()
    {
        return $this->hasOne(UserPageFeed::class);
    }
}

UserPageFeed模型:

class UserPageFeed extends Model
{
    public $incrementing = false;
    protected $guarded = ['id'];
    protected $casts = [
        'feeds' => 'array'
    ];

    public function account()
    {
        return $this->belongsTo(InstagramAccount::class,'instagram_account_id');
    }
}

你的转换有误,没有 Instagram 账户 ID,你遇到了什么错误? - user9025311
@Eminem,我没有收到任何错误。 - DolDurma
@DolDurma,看起来问题已经解决了 :-) - The Alpha
@TheAlpha 您好,感谢您在此帖子中查看我的问题。 - DolDurma
1个回答

3

您需要使用updateOrCreate()函数,并提供两个单独的参数:

$userSelectedPage->account()->updateOrCreate(
    ['instagram_account_id' => $userPageFeeds->id],
    [
        'page_name' => 'test',
        'feeds' => 'test',
        'cache_time' => Carbon::now()->addHour(6),
    ]
);

第一个参数包含 Laravel 用于查找现有 account 的属性。
第二个参数包含 Laravel 用于创建或更新 account 的属性。


1
发布问题之前我已经测试过了,但是现在它运行良好 :) - DolDurma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接