Mysql 查询Laravel选择何处数组
我有一张用户表。里面有一列名为Mysql 查询Laravel选择何处数组,mysql,laravel,select,Mysql,Laravel,Select,我有一张用户表。里面有一列名为city\u id。 在city\u id列中,数据存储如下:例如:[“12,54,87,18”] 现在我想选择其city\u id存在或等于$postcity变量的用户。 例如: 我的选择代码: $usermatchings = DB::table('users') ->Where('city_id', $postcity )
city\u id
。
在city\u id
列中,数据存储如下:例如:[“12,54,87,18”]
现在我想选择其city\u id
存在或等于$postcity
变量的用户。
例如:
我的选择代码:
$usermatchings = DB::table('users')
->Where('city_id', $postcity )
->get();
foreach ($usermatchings as $usermatching) {
$recipients = $usermatching->phone;
}
dd($recipients);
但是不工作。。。请引导我。谢谢你你可以像中所述那样使用
。下面的代码可能会帮助您:
$usermatchings = DB::table('users')
->whereRaw('FIND_IN_SET(?,city_id)', [$postcity])
->get();
注意:如果要将结果保存在数组中,则应聚合它,而不是覆盖它
foreach ($usermatchings as $usermatching) {
$recipients[] = $usermatching->phone;
}
假设:
- 数据类型或
city\u id
列是json
- cast是在模型上定义的
- 不使用sqlite作为数据库
类用户扩展模型
{
受保护的$casts=['city_id'=>'array'];
}
您可以使用whereJsonContains
$usermatchings=DB::table('users'))
->其中JsonContains('city_id',$postcity)
->get();
//获取所有电话(号码)的数组
$recepients=$usermatchings->pull('phone')->all();
拉威尔医生:是的!太好了,谢谢。但是只转储一个用户的电话(虽然我有许多用户具有相同的条件)pluck()
方法用于查询上的get()
返回的收集。因此,它将从集合的所有元素中提取phone
的值,并返回一个仅包含phone值的集合。我向Twilio功能发送$recipients
,以发送短信<代码>返回($this->sendmamin($body,$recipients))代码>但获取错误:传递给Twilio\Rest\Api\V2010\Account\MessageList::create()的参数1必须是在
此my函数`私有函数sendMessageAmin($message,$recipients)中调用的字符串、给定数组类型{$account_sid='******';$auth_token='********$twilio_number='******';$client=新客户端($account_sid,$auth_token);$client->messages->create($recipients,['from'=>$twilio_number,'body'=>$message]);}`我不知道Twilio api,但如果您需要以逗号分隔的值字符串形式发送收件人,可以在集合上使用join()
,而不是使用all()
转换为数组,如$recepients=$usermatchings->pull('phone')->join(','))这不是一个很好的解决方案,它是不可靠的,因为它会返回包含<代码>的行[[ 540 ]、“541”、“542”、“1054”] /代码>等等。您应该考虑通过编写<代码>城市< /代码>表并关联许多关系(与<代码> CITYYUSER < /COD>表)一起重新组织结构。存储当前关系的地方。这将大大加快速度。
foreach ($usermatchings as $usermatching) {
$recipients[] = $usermatching->phone;
}