Search code examples
laravellaravel-livewire

(livewire-datatables) Can't access to my two relationships to the same model


I have two foreign key related to the same table When I try to add these two columns to datatable all data resolve from only the first one of them.

My code

cities

$table->id();
$table->string('name');

trips

$table->id();
$table->foreignId('from_ctiy_id')->references('id')->on('cities');
$table->foreignId('to_ctiy_id')->references('id')->on('cities');

in Trip model I make two relationships

public function from_ctiy()
{ return $this->belongsTo(City::class, 'from_ctiy_id'); }
public function to_ctiy()
{ return $this->belongsTo(City::class, 'to_ctiy_id'); }

It works fine I can access to these two columns normally

$trip->from_city->name;
$trip->to_city->name;

But when I create columns in livewire-datatable

Column::name('from_city.name')->lable('From'),
Column::name('to_city.name')->lable('To'),

I get two columns table the same data from only the first one of them

From To
Fcity Fcity
Fcity Fcity

While should I get Fcity and Tcity


Solution

  • 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")
        ];
    }