Laravel updateOrCreate on OneToOne relationShip

。_饼干妹妹 提交于 2019-12-24 05:22:10

问题


in my web application i have this models:

InstagramAccount.php 
UserPageFeed.php

each InstagramAccount has one record into UserPageFeed and each UserPageFeed belongs to one record into InstagramAccount, then that's one to one relationship,

PROBLEM:

my below code couldn't update existing row on table and create again

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

or this code:

$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 table structure:

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

with this index:

"Keyname":user_page_feeds_instagram_account_id_foreign  "Column":instagram_account_id

instagram_accounts table structure:

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

InstagramAccount model:

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 model:

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

回答1:


You have to use updateOrCreate() with two separate parameters:

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

The first parameter contains the attributes that Laravel uses to find the existing account.
The second parameter contains the attributes that Laravel uses to create or update the account.



来源:https://stackoverflow.com/questions/50771638/laravel-updateorcreate-on-onetoone-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!