show related table columns in all select of model laravel

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-25 07:59:00

问题


I want show related table columns (customers.name) in all select of model (User) laravel. I use accessor laravel.

user table:

id    name    customer_id
1     hassan  1

customer table:

id    name
1     customer1

now use

$user = Auth::user();
return $user;

I want show:

id: 1,
name: "hassan",
customer_id: {
    id: 1,
    name: "customer1"
}

but show this error:

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);
    }
}

回答1:


So, you want to get customer name from users table based on customer_id in users.

In User.php model

public function customer(){
    return $this->hasOne(Customer::class,'id','customer_id');
}

Then,

$user = Auth::user();
$user->customer;



回答2:


Seems like this is a known issue (https://github.com/FrozenNode/Laravel-Administrator/issues/879).

I would suggest, after getting your ::all() result, you loop through it and call $user->customer.

foreach($result as $user) $user->customer;



回答3:


You should remove the $casts property. There is no way an integer can be converted to an array directly from the database, as the casts property is immediately used when selecting attributes from the database.

Also, there is no need for the getCustomerIdAttribute method, as the customer will be automatically be converted to a fictive attribute called 'customer'.

In short: just defining the customer relationship is enough. It should return the requested output except for it being called 'customer' instead of 'customer_id'.




回答4:


I find answer.

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',
];


来源:https://stackoverflow.com/questions/40327812/show-related-table-columns-in-all-select-of-model-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!