【发布时间】:2017-03-12 16:30:49
【问题描述】:
我想在模型(用户)laravel 的所有选择中显示相关的表列(customers.name)。
我使用访问器 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() 失败
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);
}
}
【问题讨论】:
-
解释清楚。你想得到什么?
-
编辑答案,请再次显示。谢谢。
-
如果你有好的解决方案(除了访问器 laravel ),请解释一下。
标签: laravel eloquent foreign-key-relationship