2016-10-30 44 views
0

相關表列(customers.name)在所有選擇的模型(用戶)laravel。 我使用訪問器laravel。顯示所有選擇模型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" 
} 

但顯示這個錯誤:

失敗調用應用程序\用戶:: 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); 
    } 
} 
+0

解釋清楚,你想得到什麼? –

+0

編輯答案,請再次顯示。謝謝。 – HassanDL

+0

如果你有很好的解決方案(accessor laravel除外), 請說明。 – HassanDL

回答

0

所以,要根據用戶的CUSTOMER_ID從用戶表中獲取的客戶名稱。

在user.php的模型

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

然後,

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

我想使用:: all()。 – HassanDL

0

您應該刪除$ casts屬性。無法直接從數據庫將整數轉換爲數組,因爲在從數據庫中選擇屬性時會立即使用casts屬性。

此外,不需要getCustomerIdAttribute方法,因爲客戶將被自動轉換爲名爲'customer'的虛構屬性。

總之:僅僅定義客戶關係就足夠了。它應該返回請求的輸出,除了被稱爲'customer'而不是'customer_id'。

0

我找到答案。

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', 
]; 
相關問題