[英]Join 2 tables in Eloquent Laravel 5.2 - How to retrieve all data from both two tables?
I have two tables我有两张桌子
1. 1.
Game Console
-- console_id
-- console_name
2. 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我编写此查询以获取所有带有 console_name 的游戏标签
GameLabel::with('console')->get();
But I am only getting records from game_label table, not from console table.但我只从 game_label 表中获取记录,而不是从控制台表中获取记录。
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.我不想用那个。
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 in属于第一个console_id代表游戏控制台表id和第二个console_id代表game_label表console_id
now in controller现在在控制器中
GameLabel::with('console')->get();
i think all data will be availbale in array under console key我认为所有数据都可以在控制台键下的数组中使用
Yes, its under console key.是的,它在控制台键下。 I found the solution.我找到了解决方案。 the console name was not getting in the view so get the console name in view like this控制台名称没有出现在视图中,所以像这样在视图中获取控制台名称
foreach($game_label as $getGameLabel){
echo $getGameLabel->console->console_name;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.