laravel 检索列中以逗号分隔的多个值作为单独的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25952804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:08:10  来源:igfitidea点击:

laravel retrieve multiple values separated by commas in a column as separate values

phplaraveleloquentblade

提问by 001221

Hi I have a column in my database called client_websitein my clientdatabase and in some cases there are multiple website links, these are separated by commas as so:

嗨,我的数据库中有一个列在我的数据库client_websiteclient,在某些情况下有多个网站链接,这些链接用逗号分隔,如下所示:

www.link1.com, www.link2.com, www.link3.com 

I query the my Projects controller first as I bring

当我带来时,我首先查询我的 Projects 控制器

   @foreach ($clients as $client)   
   {{ $client->client_name }}
    {{ $client->email }}
   {{ $client->client_website }}
   @endforeach

It literally is printed out as below:

它的字面打印如下:

www.link1.com, www.link2.com, www.link3.com 

and when I wrap it in a <a>tag it fills them the hrefwith all three links, is there anyway I can strip about the commas and spilt them into three separate entities?

当我将它包装在一个<a>标签中时,它会href用所有三个链接填充它们,无论如何我可以去掉逗号并将它们溢出到三个单独的实体中吗?

回答by aFreshMelon

You would have to put a second foreach in there which is sort of dirty but it does work. So you would put another foreach and then on the exploded string of websites and that will make an anchor for all websites.

您将不得不在其中放置第二个 foreach,这有点脏,但确实有效。因此,您可以将另一个 foreach 然后放在爆炸的网站字符串上,这将为所有网站制作一个锚点。

Imagining these are the clients websites:

想象这些是客户网站:

www.link1.com, www.link2.com, www.link3.com

www.link1.com、www.link2.com、www.link3.com

Your code would be like this:

你的代码是这样的:

@foreach ($clients as $client)   
   {{ $client->client_name }}
   {{ $client->email }}
      @foreach (explode(', ', $client->client_website) as $client_website)
          {{ $client_website }}
      @endforeach
@endforeach

This would output:

这将输出:

Client nameClient emailwww.link1.comwww.link2.comwww.link3.com

客户名称Client emailwww.link1.comwww.link2.comwww.link3.com

You can then add all sorts of styling around it. It would work for any number of clients and any number of websites. Just notice that the list of websites needs to be seperated by commas with a trailing space.

然后,您可以在它周围添加各种样式。它适用于任意数量的客户和任意数量的网站。请注意,网站列表需要用逗号和尾随空格分隔。

回答by Razor

In addition, I recommend you define an accessorin this case:

此外,我建议您在这种情况下定义一个访问器

class Client extends Eloquent {

    public function getClientWebsiteAttribute($value)
    {
        return explode(', ', $value);
    }

}


@foreach ($clients as $client)   
   {{ $client->client_name }}
   {{ $client->email }}
      @foreach ( $client->client_website as $client_website)
          {{ $client_website }}
      @endforeach
@endforeach