jeudi 20 août 2020

How can I relate BelongsTo with two columns, correctly two Laravel Eloquent models?

I have a base table with two columns, table_name and table_id, yes table name is tablea, the relation should take the table_id and take the TableA model, but if the table_name is tableb, the relation should take table_id to get the relation.

Relations Model Base

   public function tablea()
    {
        return $this->belongsTo(TableA::class, 'table_id')
        ->join('basetable', function($join)
        {
            $join->on('basetable.table_id', '=', 'tablea.id');
            $join->where('basetable.table_name','tablea');
        });
    }

    public function tableb()
    {
        return $this->belongsTo(TableB::class, 'table_id')
        ->join('basetable', function($join)
        {
            $join->on('basetable.table_id', '=', 'tableb.id');
            $join->where('basetable.table_name','tableb');
        });
    }

Controller

BaseModel::with('tablea','tableb')->get();

I have the following code but it always brings me the table_id of TableA, even though in table_name it is tableb. How can I achieve this. ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3j1SCRK
via IFTTT

Aucun commentaire:

Enregistrer un commentaire