(livewire-datatables) 无法访问我对同一模型的两个关系
(livewire-datatables) Can't access to my two relationships to the same model
我有两个与同一个相关的外键table
当我尝试将这两列添加到 datatable 时,所有数据仅从其中的第一个解析。
我的代码
城市
$table->id();
$table->string('name');
行程
$table->id();
$table->foreignId('from_ctiy_id')->references('id')->on('cities');
$table->foreignId('to_ctiy_id')->references('id')->on('cities');
在 Trip 模型中我建立了两个关系
public function from_ctiy()
{ return $this->belongsTo(City::class, 'from_ctiy_id'); }
public function to_ctiy()
{ return $this->belongsTo(City::class, 'to_ctiy_id'); }
没问题 我可以正常访问这两列
$trip->from_city->name;
$trip->to_city->name;
但是当我在 livewire-data 中创建列时table
Column::name('from_city.name')->lable('From'),
Column::name('to_city.name')->lable('To'),
我从第一列中得到两列table相同的数据
From
To
Fcity
Fcity
Fcity
Fcity
我应该得到 Fcity 和 Tcity
U have to build manually the join query like below.
public function builder()
{
return Trip::query()
->leftJoin('City as c1', 'from_ctiy_id', 'c1.id')
->leftJoin('City as c2', 'to_ctiy_id', 'c2.id');
}
public function columns()
{
return [
Column::name('c1.name')->label("From"),
Column::name('c2.name')->label("To")
];
}
我有两个与同一个相关的外键table 当我尝试将这两列添加到 datatable 时,所有数据仅从其中的第一个解析。
我的代码
城市
$table->id();
$table->string('name');
行程
$table->id();
$table->foreignId('from_ctiy_id')->references('id')->on('cities');
$table->foreignId('to_ctiy_id')->references('id')->on('cities');
在 Trip 模型中我建立了两个关系
public function from_ctiy()
{ return $this->belongsTo(City::class, 'from_ctiy_id'); }
public function to_ctiy()
{ return $this->belongsTo(City::class, 'to_ctiy_id'); }
没问题 我可以正常访问这两列
$trip->from_city->name;
$trip->to_city->name;
但是当我在 livewire-data 中创建列时table
Column::name('from_city.name')->lable('From'),
Column::name('to_city.name')->lable('To'),
我从第一列中得到两列table相同的数据
From | To |
---|---|
Fcity | Fcity |
Fcity | Fcity |
我应该得到 Fcity 和 Tcity
U have to build manually the join query like below.
public function builder()
{
return Trip::query()
->leftJoin('City as c1', 'from_ctiy_id', 'c1.id')
->leftJoin('City as c2', 'to_ctiy_id', 'c2.id');
}
public function columns()
{
return [
Column::name('c1.name')->label("From"),
Column::name('c2.name')->label("To")
];
}