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
以下是錯誤
準確地說'備用'表的名稱是什麼,用戶ID外鍵列的名稱是什麼? –
備件表是'備件',該外鍵是'retailer_id',它引用了用戶表 – hEShaN
這可能是問題所在。對於'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 –