【问题标题】:Laravel 4 where like clauseLaravel 4 where like 子句
【发布时间】:2013-06-30 04:31:20
【问题描述】:
    public function getIndex()
        {


// Get all the blog posts
        /*$posts = Post::with(array(
            'author' => function($query)
            {
                $query->withTrashed();
            },
        ))->orderBy('created_at', 'DESC')->paginate(10);*/


        $posts =Post::with(array('search' => function($query)
        {
            $query->where('title', 'like', '%Lorem ipsum%')->withTrashed();
        }))->orderBy('created_at', 'DESC')->paginate(10);


        // Show the page
        return View::make('frontend/blog/index', compact('posts'));

    }

这是我在 Controller 中的代码。我正在使用 GitHub 上提供的入门包。

我为这个控制器创建了这个模型

public function search()
{
    return $this->belongsTo('Post', 'user_id');
}

问题是它没有获取标题包含“Lorem ipsum”的结果。它只是打印表中的所有值。

我怎样才能实现它以仅获取包含我的标签/关键字的值。我这样做是为了向 laravel 网站添加搜索选项

【问题讨论】:

    标签: mysql laravel laravel-4 eloquent


    【解决方案1】:

    为什么不为此创建一个范围?你读过scopes docs吗? 这是一个示例,我将如何实现这一目标:

    范围:

    public function scopeTagged($query, $tag)
    {
        return $query->where('title', 'LIKE', '%' . $tag . '%');
    }
    

    并修改您的操作:

    public function getIndex()
    
    {
    
        $posts = Post::tagged($lorem_ipsum)->withTrashed()->orderBy('created_at', 'DESC')->paginate(10);
    
        // Show the page
        return View::make('frontend/blog/index', compact('posts'));
    
    }
    

    【讨论】:

    • 哇.. 好像我有点晚了,虽然这个信息会有用
    【解决方案2】:

    试试这个...

        $posts =Post::with(array('search' => function($query)
        {
            $query->raw_where("title LIKE '%Lorem ipsum%")->withTrashed();
        }))->orderBy('created_at', 'DESC')->paginate(10);
    

    或者类似的东西......

    $search 是您的输入

     Post::raw_where("match (`title`) against (?)", array($search))
        ->orderBy('created_at', 'DESC')->paginate(10);
    

    编辑

    这个呢?

     Post::where(DB::raw('MATCH(`title`)'),'AGAINST', DB::raw('("+'.implode(' +',$search).'" IN BOOLEAN MODE)->orderBy('created_at', 'DESC')->paginate(10);
    

    【讨论】:

    • 我已经在另一个问题中看到了您的帖子。这给了我错误
    • 调用未定义的方法 Illuminate\Database\Query\Builder::raw_where()
    • 在 Laravel 4 中,方法是 whereRaw 而不是 raw_where。浏览一下源代码会很快告诉您方法名称。
    • 您在最后一个 % 之后还缺少一个分号
    【解决方案3】:

    我认为这是 Laravel Eager 加载约束实现的问题:

    参考:-

    https://github.com/laravel/laravel/pull/1069
    
    https://github.com/laravel/laravel/pull/946
    

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2019-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多