在所有选择的模型laravel中显示相关表格列 [英] show related table columns in all select of model laravel
本文介绍了在所有选择的模型laravel中显示相关表格列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在所有选择的模型(用户)laravel中显示相关表格列( customers.name
)。
我使用访问器laravel。
I want show related table columns (customers.name
) in all select of model (User) laravel.
I use accessor laravel.
用户表:
id name customer_id
1 hassan 1
客户表:
id name
1 customer1
现在使用
$user = Auth::user();
return $user;
我要显示:
id: 1,
name: "hassan",
customer_id: {
id: 1,
name: "customer1"
}
但显示此错误:
失败调用App\User :: jsonSerialize()
Failed calling App\User::jsonSerialize()
class User extends Authenticatable
{
use EntrustUserTrait;
/**
* Get the user's customer name.
*
* @param string $value
* @return array
*/
public function getCustomerIdAttribute($value)
{
return [
'id' => $value,
'name' => $this->customer->name
];
}
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'customer_id' => 'array',
];
/**
* Get the customer record associated with the user.
*/
public function customer()
{
return $this->belongsTo(Customer::class);
}
}
推荐答案
找到答案。
public function getCustomerNameAttribute()
{
return $this->attributes['customer_name'] = ($this->customer ? $this->customer->name : null);
}
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [
'customer_name',
];
这篇关于在所有选择的模型laravel中显示相关表格列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文