繁体   English   中英

Laravel在一对一关系上更新或创建

[英]Laravel updateOrCreate on OneToOne relationShip

在我的Web应用程序中,我有以下模型:

InstagramAccount.php 
UserPageFeed.php

每个InstagramAccount都有一个记录到UserPageFeed中,每个UserPageFeed都属于一条记录到InstagramAccount中,那么这是one to one关系,

问题:

我下面的代码无法更新表上的现有行并再次创建

$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),
]);

user_page_feeds表结构:

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');
    }
}

您必须使用带有两个单独参数的updateOrCreate()

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM