首页 文章

如何在Eloquent中有效地仅选择Belongs To Many关系的ID?

提问于
浏览
1

如果我有一个Users表和Tags表,以及一个Belongs To Many关系的数据透视表,我如何使用Eloquent只加载关系的ID?

如果我执行 User::with('tags') ,这将在数据透视表上进行连接,并在标记表上进行连接 . 但是,在我的情况下这是不必要和低效的,因为我希望只能从数据透视表中选择标记的ID,而不是在Tags表中的其他列 . 换句话说,我只希望它从Users到Users_Tags进行单一连接 .

谢谢 .

2 回答

  • 1

    好的,因为@ WereWolf的建议不正确(如果有自定义键,第一个会导致错误,第三个可能是错误的),这里有你的选项,不能获取相关的模型 .

    从最明显的开始:

    // 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');
    }
    
  • 1

    试一试(未经测试):

    $user = User::query();
    $ids = $user->getRelation('tags')->getRelatedIds();
    

    或者类似的东西(但在 tags 调用期间会做一些额外的查询):

    $user = User::find(1);
    $ids = $user->tags->fetch('id');
    

    更新:(另一种方式)

    $user = User::find(1);
    $ids = array_fetch(DB::table($user->joiningTable('tag'))
                           ->where($user->getForeignKey(), $user->getKey())
                           ->get(), 'tag_id');
    

相关问题