php - Laravel 在 OneToOne 关系上更新或创建

标签 php laravel laravel-5.6

在我的网络应用程序中我有这个模型:

InstagramAccount.php 
UserPageFeed.php

每个 InstagramAccount 在 UserPageFeed 中有一条记录,并且每个 UserPageFeed 都属于 InstagramAccount 中的一条记录,那么这是一对一关系,

问题:

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

或此代码:

$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 用来查找现有的属性 账号.
第二个参数包含 Laravel 用于创建或更新 account 的属性。

关于php - Laravel 在 OneToOne 关系上更新或创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50771638/

相关文章:

php - mysql_real_escape_string 未显示错误

php - 存储代码 i mysql

laravel - 如何实现 Laravel Redis 速率限制

php - 在php中对上传文件的哈希内容

laravel - Laravel 中使用紧凑值重定向

php - 如何在 NetBeans 中完成 jQuery 代码?

php - Symfony2 表格 : How to render the same element twice in the same view

Laravel 从其他表获取信息

laravel - Laravel 中的自定义主键不起作用

php - 在 Laravel 5 中批量插入