首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel updateOrCreate on OneToOne relationShip

Laravel updateOrCreate on OneToOne relationShip
EN

Stack Overflow用户
提问于 2018-06-09 06:40:05
回答 1查看 2.1K关注 0票数 3

在我的web应用程序中,我有这样的模型:

代码语言:javascript
复制
InstagramAccount.php 
UserPageFeed.php

每个InstagramAccount都有一个UserPageFeed记录,每个UserPageFeed都属于InstagramAccount中的一个记录,这就是one to one关系,

问题:

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

代码语言:javascript
复制
$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),
]);

或者这个代码:

代码语言:javascript
复制
$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表结构:

代码语言:javascript
复制
id                     ->Primary
instagram_account_id   ->Index
feeds
page_name
cache_time
created_at
updated_at 

使用此索引:

代码语言:javascript
复制
"Keyname":user_page_feeds_instagram_account_id_foreign  "Column":instagram_account_id

instagram_accounts表结构:

代码语言:javascript
复制
id                     ->Primary
user_id                ->Index
uid
fid
proxy
avatar
username
password
checkpoint
account_data
people_data
status
created_at
updated_at 

InstagramAccount模型:

代码语言:javascript
复制
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模型:

代码语言:javascript
复制
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');
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-09 12:54:06

您必须在两个单独的参数中使用updateOrCreate()

代码语言:javascript
复制
$userSelectedPage->account()->updateOrCreate(
    ['instagram_account_id' => $userPageFeeds->id],
    [
        'page_name' => 'test',
        'feeds' => 'test',
        'cache_time' => Carbon::now()->addHour(6),
    ]
);

第一个参数包含Laravel用于查找现有account的属性。

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50771638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档