如何仅选择一个具有雄辩模型范围的列?
我有两张桌子。两者之间有一定的关系。我正在尝试查询两者以获得匹配的结果。如果结果也有与参数值匹配的列,则会检查该结果。 我正在用范围尝试它并且它有效。我只需要第二个表中的一列,当我得到结果时,我尝试将其用作第一个表中的列。 因此,代码有效,我得到了结果,但我试图过滤以仅从第二个表中选择一列。
我的代码看起来像那样。
我的控制器:
public function test()
{
$UID='LQuupgYvnuVzbEoguY4TF8bnHUU2';
$event=Events::withState($UID)->get();
echo $event;
}
我的模型范围函数:
public function scopeWithState($query,$UID){
return $query->with(['EventLiked' => function($query) use($UID) {
$query
->where('EventLiked.UID', $UID)
;
}]);
}
我的 hasMany 关系函数:
public function EventLiked()
{
return $this->hasMany(EventLiked::class,'EID','ID')->select('State','UID','EID');
}
I got two tables. Both have a relationship to each other. I´m trying to query both to get the matching results. This results get checked if they also have an column which matches with a parameter value.
I´m trying it with a scope and it work. I only need one column from the second table and I´m trying to use it as column in my first table when I got my result.
So the code works and I got an result but I´m trying to filter to select only one column from the second table.
My code look like that.
My controller:
public function test()
{
$UID='LQuupgYvnuVzbEoguY4TF8bnHUU2';
$event=Events::withState($UID)->get();
echo $event;
}
My model scope function:
public function scopeWithState($query,$UID){
return $query->with(['EventLiked' => function($query) use($UID) {
$query
->where('EventLiked.UID', $UID)
;
}]);
}
My hasMany relationship function:
public function EventLiked()
{
return $this->hasMany(EventLiked::class,'EID','ID')->select('State','UID','EID');
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会去指定闭包内的列。
新作用域:
调用作用域:
您没有得到预期结果,因为 Laravel 将其分为 2 个查询:
因此,您只想在第二个查询中更改选择语句。不在第一个
I would go for specifying columns inside closure.
New scope:
Calling scope:
You're not getting expected results because Laravel splits it into 2 queries:
So you want to change select statement only in 2nd query. Not in a first one