用laravel模型中的关系数据替换列

时间:2017-10-11 07:37:05

标签: php database laravel eloquent

我需要知道是否可以将模型中的字段数据更改为其他内容? ?

例如我有created_by列,其中的数据是1

我已经创建了与用户模型的关系,一切都很好,但我需要将created_by替换为其用户名

有什么建议吗? ?

这是我试过的

class PostsTranslation extends Model {


    public $appends = [ 'created_by' ];


    public function User() {

        return $this->belongsTo( 'App\User', 'created_by', 'id' )->first();

    }


    public function getCreatedByAttribute() {
        return $this->User()->name;

    }


}

错误就是这个

enter image description here

我认为$append会替换created_by值,而belongeTo启动时会将其读为null

是否有任何解决方案可以通过created_by来传递belongeTo id? ?

1 个答案:

答案 0 :(得分:0)

getCreatedByAttribute

拜托,不要。使用这种方法不仅会破坏大量执行的SQL查询,而且还会破坏人们理解代码的方式。

$translation = PostsTranslation::with('user')->find(1);
$translation->created_by->name;

如果您想以其他方式执行此操作,请应用getter / setter模式,例如:

class PostsTranslation extends Model {
     public function User() {
          return $this->belongsTo( 'App\User', 'created_by', 'id' )->first();
     }
     public function getCreatedBy() {
         return $this->User->name;
     }
}
相关问题