我无法在默认用户模型上设置雄辩的关系。备用表有一个外键,即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-> user-> name}}
@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
以下是错误
答案 0 :(得分:3)
回复你的评论:
备用表是'备件',因为外键是'retailer_id' 引用用户表
Eloquent通过检查关系方法的名称并使用_id为方法名称添加后缀来确定默认外键名称。但是,如果备用模型上的外键不是user_id,则可以将自定义键名作为第二个参数传递给belongsTo方法:
public function user()
{
return $this->belongsTo('App\User', 'retailer_id');
}
然而,最好不要让Eloquent成功地解决你的关系而不需要任何覆盖。一种方法是在Spare.php中重命名您的方法:
public function retailer()
{
return $this->belongsTo('App\User');
}
另一种方法是将该方法保留原样,并将外键列名重命名为user_id
。但在这种情况下,你当然会失去单词retailer
的语义。