【问题标题】:show related table columns in all select of model laravel在模型 laravel 的所有选择中显示相关表列
【发布时间】: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


【解决方案1】:

因此,您希望根据 users 中的 customer_id 从 users 表中获取客户名称。

在 User.php 模型中

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

那么,

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

【讨论】:

  • 我想使用 ::all()。
【解决方案2】:

似乎这是一个已知问题 (https://github.com/FrozenNode/Laravel-Administrator/issues/879)。

我建议,在获得 ::all() 结果后,循环遍历它并调用 $user->customer。

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

【讨论】:

  • 我以前使用过这段代码,但我想找到一个好的解决方案。谢谢。
【解决方案3】:

您应该删除 $casts 属性。整数无法直接从数据库中转换为数组,因为从数据库中选择属性时会立即使用 casts 属性。

此外,不需要 getCustomerIdAttribute 方法,因为客户将自动转换为名为“客户”的虚拟属性。

简而言之:只需定义客户关系就足够了。它应该返回请求的输出,除了它被称为“customer”而不是“customer_id”。

【讨论】:

    【解决方案4】:

    我找到答案了。

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

    【讨论】:

      猜你喜欢
      • 2014-06-01
      • 2016-05-22
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 2013-08-07
      • 2022-07-26
      相关资源
      最近更新 更多