【问题标题】:How to include a column or columns from a child Model which belongTo parent Model in Eloquent?如何在 Eloquent 中包含属于父模型的子模型中的一列或多列?
【发布时间】:2017-04-21 09:28:08
【问题描述】:

在用户模型中:

public function role(){

    return $this->hasOne('App\Model\Roles','id','role_id');

}

在角色模型中:

public function user(){

    return $this->belongTo('App\Model\Users');

}

在方法中:

$query = Users::where('id', $id)->get();

我得到了什么(在 JSON 中):

[{"id":2,"user_name":"hazardgeek","user_email":"nwasuper@example.com","user_phone":"*******","user_password":"*********","remember_token":"*****","role_id":2}]

我真正想要的:

我想要 Roles 模型中的 role_title 列,而不是 Users 表中的 role_id。 像这样, ......user_password":"thesupernwa","remember_token":null,"role_title":"customer"}]

我怎样才能做到这一点?谢谢。

【问题讨论】:

    标签: php laravel eloquent relationship has-one


    【解决方案1】:

    在 User.php 模型中

    public function User(){
         protected $appends = ['role_title'];
    
         public function getRoleTitleAttribute(){
              $role = $this->getRelation('role');
              return !empty($role) ? $this->role->role_title : null;
         }
    }
    

    【讨论】:

    • 您的解决方案为我提供了一组用户模型中的一组角色模型。不替换 role_id 列。
    • 你是否在 user.php 模型中添加了protected $appends = ['role_title'];?
    • 使用$query = Users::where('id', $id)->get();,您可以获得role_title。你试过了吗?
    • 是的,我确实尝试过。仍然不能有 role_title 来替换 role_id 列
    • 它不会替换role_id,而是在数组中添加额外的属性为role_title,并且还会显示角色模型。正确检查您的阵列。
    【解决方案2】:

    我最终使用原始查询来检索正确的响应

    return DB::table('ctr_user')
                ->select('ctr_user.id AS user_id','user_name','user_email','user_phone','user_password','remember_token','ctr_role.role_title AS title')
                ->rightJoin('ctr_role', 'ctr_role.id','=','ctr_user.role_id')
                ->where('ctr_user.id','=',$id)
                ->get();
    

    这个原始查询返回的响应正是我需要使用 Eloquent 的响应。

    但还是如何?

    【讨论】:

      猜你喜欢
      • 2018-11-30
      • 2011-08-23
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 2017-08-06
      • 2018-04-03
      相关资源
      最近更新 更多