【问题标题】:How do I perform this search query in eloquent ORM如何在 eloquent ORM 中执行此搜索查询
【发布时间】:2015-06-26 08:59:04
【问题描述】:

我正在尝试使用 eloquent 中的特定用户的书签中的特定标签名称执行搜索查询:

SELECT * FROM bookmarks_tags WHERE tag_id in (SELECT id FROM tags WHERE name in ('new','please','work')) 和 bookmark_id in (SELECT id 来自用户 ID = 1 的书签)

我有以下具有关系的模型设置:

标签模型

class Tag extends Eloquent
{

   public function bookmarks()
    {
        return $this
            ->belongsToMany('Bookmark','bookmarks_tags');
    }
}

书签模型:

class Bookmark extends Eloquent {

    .....
     public function owner()
    {
    return $this->belongsTo('User','id');
    }
    public function tags()
    {
        return $this->belongsToMany('Tag','bookmarks_tags','bookmark_id','tag_id');
    }


}

最后是用户模型:

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';
    .....

    public function bookmarks()
    {
        return $this->hasMany('Bookmark','userid');
    }

}

这是我的数据库架构:

我知道我可以通过以下方式获取书签和标签 ID:

$bookmarkIDs = Auth::user()->bookmarks()->get('id');
 $tagsID = Tag::whereIn('name', $tags)->get('id');

但我不知道如何对bookmarks_tag 执行此查询。

【问题讨论】:

    标签: laravel laravel-4 orm eloquent relationship


    【解决方案1】:

    不确定我是否正确理解了您的要求,但这将为您提供属于分配了特定标签的用户的书签:

    $tags = ['new', 'please', 'work'];
    $bookmarks = Bookmark::whereHas('owner', function($q){
        $q->where('users.id', 1);
    })->whereHas('tags', function($q) use ($tags){
        $q->whereIn('name', $tags);
    })->get();
    

    或者(实际上更简单)

    $bookmarks = Bookmark::whereHas('tags', function($q) use ($tags){
        $q->whereIn('name', $tags);
    })->where('userid', 1)->get();
    

    【讨论】:

    • 您好,我不小心从 Bookmark 模型中删除了 owner() 关系。你能再看看吗?
    • 现在你把它放在标签模型中。但无论如何,如果关系被称为owner 而不是user,只需使用whereHas('owner', ...。我编辑了我的答案
    • 这是我在运行代码时得到的查询: SELECT * FROM bookmarks WHERE (SELECT count() FROM users WHERE bookmarks.id = @987654330 @.id and id = '1') >= 1 and (SELECT count() FROM tags 内部连接bookmarks_tagstags.id = bookmarks_tags.@ 987654338@ WHERE bookmarks_tags.bookmark_id = bookmarks.id and name in ('new', 'please', 'work')) >= 1
    • 不返回任何结果
    • 你确定这不是预期的结果吗?我的意思是应该有匹配的书签吗?
    猜你喜欢
    • 2013-06-19
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多