Muhammad Asim Muhammad Asim - 6 months ago 625
SQL Question

Join 2 tables in Eloquent Laravel 5.2 - How to retrieve all data from both two tables?

I have two tables

1. Game Console

-- console_id

-- console_name


2. Game Labels

-- game_label_id

-- console_id (foreign key)

-- title

-- description

-- image

-- created


GameConsole Model



namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class GameConsole extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
public $timestamps = false;
protected $table = 'console';
protected $fillable = array('console_name', 'description', 'created');
protected $primaryKey = 'console_id';

public function labels()
{
return $this->hasMany('App\Http\Models\GameLabel','console_id');
}

}




GameLabel Model



namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class GameLabel extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
public $timestamps = false;
protected $table = 'game_label';
protected $fillable = array('game_label_id','console_id', 'title','description','image', 'release_date','status','created');
protected $primaryKey = 'game_label_id';

public function console()
{
return $this->belongsTo('App\Http\Models\GameConsole','console_id');
}
}




I write this query to get all game labels with console_name


GameLabel::with('console')->get();




But I am only getting records from game_label table, not from console table.

Can any body please tell me that what query I have to write to get all records?
Please don't suggest me about query builder joins. I don't want to use that.

Answer
       namespace App\Http\Models;

        use Illuminate\Database\Eloquent\Model;

        class GameLabel extends Model
        {
            /**
             * The attributes that are mass assignable.
             *
             * @var array
             */
            public $timestamps = false;
            protected $table = 'game_label';
            protected $fillable = array('game_label_id','console_id', 'title','description','image', 'release_date','status','created');
            protected $primaryKey = 'game_label_id';

            public function console()
            {
               return $this->belongsTo('App\Http\Models\GameConsole', 'console_id', 'console_id');
           }
}

in belongs to first console_id represent Game Console table id and and second console_id represent game_label table console_id

now in controller

GameLabel::with('console')->get();

i think all data will be availbale in array under console key

Comments