簡體   English   中英

更新與Laravel 5.4上由hasOne關系鏈接的模型相關的字段

[英]Update a field related to the model linked by a hasOne relationship on Laravel 5.4

我有2張桌子, personphysicalperson person 人員表是通用表,自然人表是與人相關的特定人(因為我們也可以有代表公司的道德人)。 這兩個表通過OnetoOne關系鏈接。

表“人”:

id  |   name    |   comments    |   created_at
==============================================
1       Doe                         2017-03-30
2       Bar         Test            2017-04-05

表“自然人”:

id  |   person_id   |   surname |   birth
==============================================
1       1               John        1990-07-31
2       2               Foo         1970-01-01

現在,我建立了我的關系船,說對於1個人,我最多擁有1個自然人:

<?php
    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Person extends Model
    {
        public $timestamps = false;

        protected $table = 'person';    
        protected $primaryKey = 'id';

        public function physical()
        {
            return $this->hasOne('App\PhysicalPerson');
        }
    }
?>

我確認,在選擇時,我通過執行以下操作獲得了所需的所有數據:

<?php
    $person = Person::findOrFail(1);

    echo $person->physical->surname; // Prints John
    echo $person->name; // Prints Doe
?>

但是,當我嘗試更新我的人員(和相關的物理人員)時,我僅設法獲得了該人員的更新,並且物理原因似乎被忽略,原因不明:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Person extends Model
{
    public $timestamps = false;

    protected $table = 'person';    
    protected $primaryKey = 'id';

    public function physical()
    {
        return $this->hasOne('App\PhysicalPerson');
    }

    public static function put( $id, Request $request )
    {
        $person = self::findOrFail( $id );

        $person->name = $request->input('name');
        $person->physical->surname = $request->input('surname'); // Seems to be ignored

        $person->save();
    }
}

是否有人已經使用雄辯的關系方法設法“級聯”更新了模型?

$person = self::findOrFail( $id );
 $physicalPersion = physicalperson::where('persion_id' , '=' , $id)->get() ;
    $person->name = $request->input('name');
    $physicalPersion->surname = $request->input('surname'); 
    $physicalPersion->save() ;
    $person->save();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM