我有两张桌子 1.
Game Console
-- console_id
-- console_name
2
Game Labels
-- game_label_id
-- console_id (foreign key)
-- title
-- description
-- image
-- created
GameConsole模型
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模型
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_name的游戏标签
GameLabel::with('console')->get();
但我只是从game_label表中获取记录,而不是从控制台表中获取记录。
任何人都可以告诉我,为了获得所有记录,我必须写什么查询? 请不要向我推荐有关查询构建器连接的信息。我不想用它。
答案 0 :(得分:1)
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属于第一个console_id代表Game Console表id,第二个console_id代表game_label table console_id
现在在控制器
GameLabel::with('console')->get();
我认为所有数据都将在控制台密钥下的数组中显示
答案 1 :(得分:0)
是的,它在控制台键下。我找到了解决方案。 控制台名称未进入视图,因此请在视图中获取控制台名称
foreach($game_label as $getGameLabel){
echo $getGameLabel->console->console_name;
}