lundi 20 février 2017

Laravel 5 joining multiple tables

I am having real problems joining tables in Laravel.

I can join 2 tables but as soon as I try to join a third, i get no data

class Main extends Model
{
    protected $table = 'main';
    protected $primaryKey = 'id';

    public function test() 
    {
        return $this->hasOne('App\Models\Test', 'id', 'id');
    }

    public function row() 
    {
        return $this->hasOne('App\Models\Row', 'id', 'id');
    }
}

class Test extends Model
{
    protected $table = 'test';
    protected $primaryKey = 'id';

    public function main() 
    {
        return $this->belongsTo('App\Models\Main', 'id', 'id');
    }

    public function rows() 
    {
        return $this->hasMany('App\Models\Row', 'id', 'id');
    }
}

class Row extends Model
{
    protected $table = 'row';
    protected $primaryKey = 'id';

    public function main() 
    {
        return $this->belongsTo('App\Models\Main', 'id', 'id');
    }

    public function rows() 
    {
        return $this->belongsTo('App\Models\Test', 'id', 'id');
    }
}

I've added this to my Main model to run a query. This will output the 2 tables

public function scopeGetPart($query, somefield)
{
    return $query->with('test.main')
        ->where('somefield', somefield);
} 

This works when i run it through phpMyAdmin. I want to write this the Laravel way

SELECT * FROM
    main
        INNER JOIN test ON
            main.id = test.id
        INNER JOIN row ON
            main.id = row.id
                AND main.my_field = row.my_field
WHERE somefield = 103288



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2l0weuf
via IFTTT

Aucun commentaire:

Enregistrer un commentaire