【问题标题】:How to search strings inside Array of arrays using eloquent如何使用 eloquent 在数组数组中搜索字符串
【发布时间】:2018-11-12 10:18:28
【问题描述】:

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

[{"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

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

【问题讨论】:

    标签: arrays database laravel eloquent


    【解决方案1】:

    我认为这是因为您的控制器返回 0 个视频,因为标签从不匹配。 您正在使用 LIKE 语句,而没有使用 % 转义您的 tag 变量,因此您希望匹配 exactly 类似标签的内容,并且因为您有一个数组将标签作为永远不会发生的列。

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

    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]);
    }
    

    Here 你可以阅读更多关于 LIKE 运算符的信息:D

    【讨论】:

    • 像魅力一样工作!谢谢@GaimZz!
    • 另外,如果你使用 mysql,你应该知道在这样的列上搜索可能效率不高
    • 如果您将标签存储在一个单独的表中并且视频和标签之间具有 hasMany 关系,我会更好,然后您需要在两个表之间进行连接以查找具有特定标签
    猜你喜欢
    • 2019-02-01
    • 2011-07-22
    • 2012-06-12
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多