如何在Laravel的MySQL查询select语句中添加数组?
没问题,我来帮你搞定这个Laravel查询里添加buttons数组的问题!你现在的核心需求是把数据库中对应的按钮字段,转换成你需要的buttons数组结构,嵌套到每个elements元素里对吧?
方法一:直接在集合后追加Buttons字段
因为Laravel的get()方法返回的是集合(Collection),我们可以用集合的map()方法遍历每个查询结果,手动添加buttons数组。
假设你的Fabric表已经存储了每个按钮对应的字段(比如button_type、button_url、button_title),你可以这样写:
$message = [ "messages" => [ [ "attachment" => [ "type" => "template", "payload" => [ "template_type" => "list", "top_element_style" => "large", "elements" => Fabric::orderBy('id', 'DESC') ->where('title', 'LIKE', "%$search_term%") // 先把需要的字段(包括按钮相关)都查出来 ->select('title', 'postdate as image_url', 'company_name as subtitle', 'button_type', 'button_url', 'button_title') ->get() ->map(function($fabric) { // 给每个元素添加buttons数组 $fabric->buttons = [ [ "type" => $fabric->button_type, "url" => $fabric->button_url, "title" => $fabric->button_title ] ]; // 可选:如果不需要保留单个按钮字段,可以删除它们 unset($fabric->button_type, $fabric->button_url, $fabric->button_title); return $fabric; }) ->toArray() // 转成数组,匹配你需要的结构 ] ] ] ] ];
方法二:如果Buttons结构固定(仅URL含动态ID)
如果你的按钮类型、标题都是固定的,只有URL里的item_id对应Fabric的id,那甚至不需要查询额外字段,直接在map()里生成即可:
->map(function($fabric) { $fabric->buttons = [ [ "type" => "web_url", "url" => "https://petersapparel.parseapp.com/buy_item?item_id=" . $fabric->id, "title" => "buy item" ] ]; return $fabric; })
方法三:多按钮场景(关联模型)
如果每个Fabric对应多个按钮,建议给Fabric模型建立一个关联(比如hasMany(Button::class)),然后预加载关联数据再转换结构:
首先在Fabric模型里定义关联:
public function buttons() { return $this->hasMany(Button::class); }
然后查询时预加载并转换:
$elements = Fabric::orderBy('id', 'DESC') ->where('title', 'LIKE', "%$search_term%") ->select('title', 'postdate as image_url', 'company_name as subtitle') ->with('buttons') // 预加载按钮关联,避免N+1查询 ->get() ->map(function($fabric) { // 把关联的Button模型转成需要的数组结构 $fabric->buttons = $fabric->buttons->map(function($button) { return [ "type" => $button->type, "url" => $button->url, "title" => $button->title ]; })->toArray(); return $fabric; }) ->toArray(); // 最后组装成你需要的message结构 $message = [ "messages" => [ [ "attachment" => [ "type" => "template", "payload" => [ "template_type" => "list", "top_element_style" => "large", "elements" => $elements ] ] ] ] ];
核心思路
本质是利用Laravel集合的遍历转换能力,先拿到基础数据,再把每个元素的按钮字段转换成你需要的嵌套数组结构,最后转成普通数组即可匹配目标格式。
内容的提问来源于stack exchange,提问作者Soul Coder
相关产品推荐
相关产品推荐

