我想选择所有具有相同taggable_type
和taggable_id
的user_tag_id
。仅供参考,我不太擅长使用查询,laravel对我来说还很新,所以我还在学习。
这是我到目前为止所尝试的,
$check = Tag::whereIn('user_tag_id', function ( $query ) {
$query->select('taggable_id')->from('tags')->groupBy('user_tag_id');
})->get();
return $check;
返回这个,
"id" => 1
"user_tag_id" => 1
"taggable_type" => "AppDomainsTradeSetupModelsTradeSetup"
"taggable_id" => 1
"type" => null
"state" => null
"created_at" => "2022-11-25 01:57:42"
"updated_at" => "2022-11-25 01:57:42"
"deleted_at" => null
"id" => 6
"user_tag_id" => 1
"taggable_type" => "AppDomainsTradeModelsTrade"
"taggable_id" => 1
"type" => null
"state" => null
"created_at" => "2022-11-25 02:31:24"
"updated_at" => "2022-11-25 02:31:24"
"deleted_at" => null
这是模型:
//TradeSetup model
public function userTag()
{
return $this->hasMany(UserTag::class);
}
public function tags()
{
return $this->morphMany(Tag::class, 'taggable');
}
// Tag model
public function taggable()
{
return $this->morphTo();
}
public function userTag()
{
return $this->belongsTo(UserTag::class);
}
除了我不知道如何只返回,例如user_tag_id taggable_type = TradeSetup和taggable_id = 1
基本上,我怀疑查询看起来像这样
SELECT USER_TAG_ID
FROM TAGS
WHERE (TAGGABLE_ID = 1) AND
WHERE (TAGGABLE_TYPE = TRADESETUP)
所以我怀疑它只会返回基于user_tag_id的所有记录,其中taggable_id = 1和taggable_type = TradeSetup。
所以如果我理解正确的话,你对标签模型有一个用户关系。那么查询应该是这样的
Tag::whereHas('user_tag_id', function ($query) {
$query->where('taggable_id', 1)->where('taggable_type', 'AppDomainsTradeSetupModelsTradeSetup');
})->get();
如果我误解了你的模型设置,请在评论中告诉我,以便我可以编辑答案,干杯!
编辑1 #因此,据我所知,你只需要返回具有UserTag关系的标签你可以像这样做
Tag::whereHas('userTag')->where('taggable_id', 1)->where('taggable_type', 'AppDomainsTradeSetupModelsTradeSetup')->get()