// for single model:
$user = User::first();
$user->tags()->getRelatedIds(); // select id from related table -> join
这是您可以使用的,但它不是答案,因为您想要急于加载这些ID .
话虽这么说,你需要为数据透视表创建另一个模型:
// UserTag model
protected $table = 'user_tag';
// this is not required, just to make it read-only
public static function boot()
{
parent::boot();
static::saving(function() {
return false;
}
}
// User model
public function tagsPivot()
{
return $this->hasMany('UserTag')->select('tag_id', 'user_id'); // appropriate keys here
}
public function getTagsIds()
{
return $this->tagsPivot->lists('tag_id');
}
// then you can do this:
$users = User::with('tagsPivot')->get(); // no join, select category_id from pivot table
foreach ($users as $user)
{
$user->getTagsIds();
}
.
您还可以根据自己的喜好对用户模型进行一些更改:
// to be able to do this:
$users = User::with('tagsIds')->get();
foreach ($users as $user)
{
$user->tagsIds;
}
// User model
public function tagsIds()
{
return $this->hasMany('UserTag')->select('tag_id', 'user_id'); // appropriate keys here
}
public function getTagsIdsAttribute()
{
if ( ! array_key_exists('tagsIds', $this->relations)) $this->load('tagsIds');
return $this->getRelation('tagsIds')->lists('tag_id');
}
2 回答
好的,因为@ WereWolf的建议不正确(如果有自定义键,第一个会导致错误,第三个可能是错误的),这里有你的选项,不能获取相关的模型 .
从最明显的开始:
这是您可以使用的,但它不是答案,因为您想要急于加载这些ID .
话虽这么说,你需要为数据透视表创建另一个模型:
.
您还可以根据自己的喜好对用户模型进行一些更改:
试一试(未经测试):
或者类似的东西(但在
tags
调用期间会做一些额外的查询):更新:(另一种方式)