【发布时间】:2020-03-02 17:25:49
【问题描述】:
我不太擅长这个问题。
我有两张桌子。买家和追踪者。
在跟踪器表中我有这些列
id, buyer_id, style_name
买家表是
id, 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)'
它在买家表中寻找一个 tracker_id,但我只是使用它的 id 检索一个。我做错了什么?
这是trackers的迁移文件
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
谢谢。
【问题讨论】:
标签: laravel eloquent laravel-6