我在这个问题上不是很好。
我有两个桌子。买家和追踪者。
在跟踪器表中,我有这些列
id, buyer_id, style_name
而买方表是
id, buyer_name
当我检索并显示跟踪器列表时,我也希望能够显示Buyer_name。
在我的Buyer.php模型中
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tracker extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $table = 'trackers';
protected $fillable = [
'buyer_id',
'style_name',
];
public function buyer()
{
return $this->hasOne('App\Buyer');
}
}
我用工匠修补匠进行测试。因此,代码为;
$tracker = Tracker::find(1)->buyer;
但是我得到这个错误
Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'buyers.tracker_id' in 'where clause' (SQL: select * from `buyers` where `buyers`.`tracker_id` = 1 and `buyers`.`tracker_id` is not null limit 1)'
它正在Buyers表中查找tracker_id,但我只是一个使用其ID进行检索的人。我在做什么错了?
这是跟踪器的迁移文件
public function up()
{
Schema::create('pattern_room_trackers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('buyer_id');
$table->string('style_name');
$table->foreign('buyer_id')
->references('id')
->on('buyers')
->onDelete('cascade');
});
}
我也不知道如何在刀片视图中显示此内容。
TrackerController.php
public function index()
{
$trackers = Tracker::latest()->paginate(5);
return view('trackers.index',compact('trackers'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
index.blade.php
@foreach ($trackers as $tracker)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $tracker->style_name }}</td>
<td>{{ $tracker->buyer_name }}</td>
</tr>
@endforeach
谢谢。
答案 0 :(得分:1)
您需要使用belongsTo
关系。买方是Tracker的父母。
public function buyer()
{
return $this->belongsTo('App\Buyer','buyer_id');
}
和刀片中
<td>{{ $tracker->buyer->buyer_name }}</td>
阅读laravel文档here,了解一对多的逆向关系。