简体   繁体   English

如何从Laravel中的表中获取逗号分隔的值

[英]How to get comma separated values from a table in Laravel

This is my Categories Table : 这是我的类别表

id  | name
 1    a
 2    b
 3    c
 4    d

In which I need to get the values of 1 and 2 in comma separated manner, ie a,b . 我需要以逗号分隔的方式获取值12 ,即a,b

I tried something like this: 我尝试过这样的事情:

$ids = array('0'=>1,'1'=>2);
\DB::select('SELECT group_concat(name) as name from category where id = ?', ($ids));

But it always returns the first value (ie, a ) 但是它总是返回第一个值(即a

I need the resultant values to be like this: a,b . 我需要这样的结果值: a,b

How could I do this either using normal query or by Laravel? 如何使用普通查询或Laravel执行此操作?

Thank you. 谢谢。

What you want is a kind of concatenation that can be achieved by using GROUP_CONCAT like: 您想要的是一种可以通过使用GROUP_CONCAT来实现的连接,例如:

SELECT GROUP_CONCAT(name) FROM category where id IN(1,2)

Reference 参考

Explanation: here GROUP_CONCAT(name) concat name as name1, name2 ... for the WHERE condition matched 说明:在此处GROUP_CONCAT(name) concat名称为name1,name2 ...,用于匹配WHERE条件

Try this using simple concat. 使用简单的concat尝试一下。 You can concat as much as columns separated by commas. 您最多可以合并用逗号分隔的列。

Query - select concat(id,",",name) as name from category where id = ? 查询- select concat(id,",",name) as name from category where id = ?

Try this 尝试这个

$data = \DB::table("articles")
   ->select("title")
   ->whereRaw("find_in_set('find value',colum_name)")
   ->get();

POST or GET data field user_id = 1,2,3; POST或GET数据字段user_id = 1,2,3;

$user_array = explode(',',Input::get('user_id')); OR $user_array = explode(',',Input::POST('user_id'));
$all_user =   User::WhereIn('user_id',$user_array)->get();

Get all user which have User ID 1,2 and 3. 获取所有具有用户ID 1,2和3的用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM