nicolaslopezj / searchable

A php trait to search laravel models
MIT License
2.01k stars 291 forks source link

Multiple relations for the same table #135

Open devfelipereis opened 7 years ago

devfelipereis commented 7 years ago

For example:

`

'columns' => [ 'cities.name' => 10, ],

'joins' => [ 'cities' => ['patients.city_id', 'cities.id'], ], `

In my app, a Patient has the city(city_id) where it is currently living and also 'place_of_birth_id' that is where it was born.

In 'joins' array, I can not pass 'place_of_birth_id' because I'll get a duplicate key. Is there any way to do this? Thanks!

sanikkenway commented 7 years ago

I've been wondering the same, what if there are more than 1 column that related to a table

'joins' => [
'cities' => ['patients.city_id', 'cities.id'],
'cities' => ['patients.place_of_birth_id', 'cities.id'],
],

or maybe like this to avoid duplicate table

'joins' => [
'cities' => [['patients.city_id', 'cities.id'], ['patients.place_of_birth_id', 'cities.id']],
],

is it practicable?

JamesPoel commented 6 years ago

This is the reason I've abandoned implementation of this package. I have a parcels table with origin_id and destination_id - both which link to a locations table. Absolutely needed! ++

emeGuan commented 3 years ago

You can do this:

protected $searchable = [
    'columns' => [
        'inmuebles.codigo'          => 10,
        'lovs.nombre'               => 10,
        'lovs2.nombre'              => 10,
        'lovs3.nombre'              => 10,
    ],
    'joins' => [
        'lovs'                  => ['inmuebles.tipo_id','lovs.id'],
        'lovs as lovs2'         => ['inmuebles.estado_propiedad_id','lovs2.id'],
        'lovs as lovs3'         => ['inmuebles.estado_detalle_id', 'lovs3.id'],
    ]
];

public function tipo()
{
    return $this->belongsTo(Lov::class, 'tipo_id');
}

public function estado_propiedad()
{
    return $this->belongsTo(Lov::class, 'estado_propiedad_id');
}

public function estado_detalle()
{
    return $this->belongsTo(Lov::class, 'estado_detalle_id');
}

And lovs table is:

public function up()
{
    Schema::create('lovs', function (Blueprint $table) {
        $table->id();
        $table->string('nombre');
        $table->enum('tipo', [1, 2, 3, 4, 5, 6, 7, 8]);
    });
}

Test with Laravel8.