【问题标题】:How to set Eloquent relationship on default User Model如何在默认用户模型上设置 Eloquent 关系
【发布时间】: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-&gt;belongsTo('App\User', 'retailer_id');。来源:laravel.com/docs/5.3/eloquent-relationships#one-to-many-inverse
  • 感谢杰弗里。 :) 成功了
  • 很高兴能帮到你!

标签: php laravel-5 eloquent


【解决方案1】:

回复您的评论:

备件表是“备件”,因为外键是“retailer_id” 引用用户表

来自the documentation

Eloquent 通过检查关系方法的名称并在方法名称后加上 _id 来确定默认的外键名称。但是,如果 Spare 模型上的外键不是 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 这个词的语义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-23
    • 2014-12-05
    • 2013-09-15
    • 2017-09-25
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    相关资源
    最近更新 更多