如何在 eloquent ORM 中执行此搜索查询
How do I perform this search query in eloquent ORM
我正在尝试在 eloquent:
中为特定用户使用书签中的特定标签名称执行搜索查询
SELECT * FROM bookmarks_tags
WHERE tag_id in (SELECT id FROM tags
WHERE name in ('new','please','work')) and bookmark_id in (SELECT id
from bookmarks where userid = 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 执行此查询。
不确定我是否理解了您的要求,但这将为您提供属于分配了特定标签的用户的书签:
$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();
我正在尝试在 eloquent:
中为特定用户使用书签中的特定标签名称执行搜索查询SELECT * FROM
bookmarks_tags
WHERE tag_id in (SELECT id FROMtags
WHERE name in ('new','please','work')) and bookmark_id in (SELECT id from bookmarks where userid = 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 执行此查询。
不确定我是否理解了您的要求,但这将为您提供属于分配了特定标签的用户的书签:
$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();