【发布时间】:2017-12-29 07:07:21
【问题描述】:
我无法在默认 User 模型上建立 eloquent 关系。备用表有一个外键,即 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');
}
}
备用.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
以下是错误
【问题讨论】:
-
“备件”表的名称是什么,用户ID外键列的名称是什么?
-
备件表是“备件”,因为外键是“retailer_id”,它引用了用户表
-
这可能是问题所在。对于
belongsTo(),Eloquent 假设列名是方法名的snake_case 变体,后缀为_id。所以那将是user_id。要覆盖它,请在 Spare.php 中执行return $this->belongsTo('App\User', 'retailer_id');。来源:laravel.com/docs/5.3/eloquent-relationships#one-to-many-inverse -
感谢杰弗里。 :) 成功了
-
很高兴能帮到你!