首页 > 解决方案 > 如何使用 eloquent 在数组数组中搜索字符串

问题描述

所以我有一个数据库列,其中内容是这样的数组:

[{"tag_name":"example1"},{"tag_name":"example2"}, {"tag_name":"example3"}]

我想做的是检索带有特定标签的视频。所有视频页面都有特定的标签,当用户点击其中一个标签时,它会被重定向到一个视图,其中将显示具有相同标签的类似视频。

现在我有以下控制器:

public function search($tag){
    $tag = urldecode($tag);
    $videos = Video::where('tags', 'LIKE', $tag)->paginate(12);
    $settings = Detail::find(1);
    $ads = Ad::find(1);

    return view('search', ['videos' => $videos, 'settings' => $settings, 'ads' => $ads]);

}

我有以下观点(search.blade.php):

@foreach($videos as $video)

    <div class="col-lg-4 col-xs-12">

        <div class="row justify-content-center">

            <a href="{{ route('videos.videopage', $video->id) }}"><img class="articleImg" src="{{$video->imgurl}}"></a>

        </div>


        <div>
            <p class="float-left">{{$title = substr($video->title, 0, 30) . " ..."}}</p>

            <small class="duration float-right">{{$video->duration}}</small>

            <div class="progress float-right">
                <div class="progress-bar bg-success" role="progressbar" style="width: {{$video->rating}}%" aria-valuenow="{{$video->rating}}" aria-valuemin="0" aria-valuemax="100"></div>
            </div>


        </div>

    </div>  


@endforeach

问题是现在,我的视图中没有显示任何视频,即使很难,我也完全没有错误。是因为这些列有一个数组数组吗?

标签: arraysdatabaselaraveleloquent

解决方案


我认为这是因为您的控制器返回 0 个视频,因为标签从不匹配。您正在使用LIKE语句而不用 转义您的标签变量%,因此您正在寻找与标签完全相同的东西,并且因为您有一个标签数组作为永远不会发生的列。

您可以实施的一种解决方案是将您的标签更改为以下内容:

public function search($tag){
   $tag = urldecode($tag);
   $videos = Video::where('tags', 'LIKE', '%'.$tag.'%')->paginate(12);
   $settings = Detail::find(1);
   $ads = Ad::find(1);

   return view('search', ['videos' => $videos, 'settings' => $settings, 'ads' => $ads]);
}

在这里您可以阅读有关 LIKE 运算符的更多信息:D


推荐阅读