2016-11-20 88 views
1

我無法在默認用戶模型上設置雄辯關係。備用表的外鍵是UserID引用用戶表的外鍵。以下是代碼如何在默認用戶模型上設置雄辯關係

user.php的

class User extends Authenticatable 
{ 
use Notifiable; 

/** 
* The attributes that are mass assignable. 
* 
* @var array 
*/ 
protected $fillable = [ 
    'name', 'email', 'password', 
]; 

/** 
* The attributes that should be hidden for arrays. 
* 
* @var array 
*/ 
protected $hidden = [ 
    'password', 'remember_token', 
]; 

public function isAdmin() 
{ 
    return $this->type; // this looks for an admin column in your users table 
} 
public function spares() 
{ 
    return $this->hasMany('App\Spares'); 
} 

}

Spare.php

public function user() 
{ 
    return $this->belongsTo('App\User'); 
} 

SearchController.php

public function index(Request $request) 
{ 

    $spares=Spares::with('user','model') 
     ->where ('description','LIKE','%'.$request->searchName.'%') 
     ->paginate(5); 
    return View::make('browse')->with('spares', $spares); 

} 

browse.blade.php無法訪問{{$ spare->用戶>吶我}}

@foreach($spares as $spare) 

<tr> 
<td class="col-md-6"> 
<div class="media"> 
<a class="thumbnail pull-left" href="#"> <img class="media-object" 
     src='{{ asset("images/spares/$spare->imagePath") }}' 
      tyle="width: 100px; height: 100px;padding-left: 10px"> </a> 
<div class="media-body" style="padding-left: 10px;"> 

<h4 class="media-heading"><a href="#">{{$spare->description}}</a></h4> 
<h5 class="media-heading"> by <a href="#">{{$spare->user->name }}</a></h5> 
</div> 
</div> 
</td> 

<td class="col-md-1 text-center"><strong>Rs. {{$spare->price}}/=</strong></td> 

</tr> 

@endforeach

以下是錯誤

enter image description here

+0

準確地說'備用'表的名稱是什麼,用戶ID外鍵列的名稱是什麼? –

+0

備件表是'備件',該外鍵是'retailer_id',它引用了用戶表 – hEShaN

+1

這可能是問題所在。對於'belongsTo()',Eloquent假定列名是方法名的snake_case變體,後綴爲_id。所以這將是'user_id'。要重寫這個,請執行'返回$ this-> belongsTo('App \ User','retailer_id');'在Spare.php中。 來源:https://laravel.com/docs/5.3/eloquent-relationships#one-to-many-inverse –

回答

2

在回答您的評論:

備件表是外國 '零部件'鍵是'retailer_id',其中 引用用戶表

the documentation

口才通過檢查的關係,方法的名稱,後面添加_id方法名確定默認外鍵名。但是,如果在備用模式外鍵不user_id說明,您可以通過自定義鍵名作爲第二個參數屬於關聯方法:

public function user() 
{ 
    return $this->belongsTo('App\User', 'retailer_id'); 
} 

但是,它可能會更好,使雄辯只是在解決成功的在沒有必要時沒有任何覆蓋的關係。一種方法是在Spare.php重命名你的方法:

public function retailer() 
{ 
    return $this->belongsTo('App\User'); 
} 

另一個辦法是離開這個方法是和外鍵列名重命名爲user_id。但在這種情況下,您當然會失去retailer這個詞的語義。