简体   繁体   English

Laravel 4喜欢的条款

[英]Laravel 4 where like clause

    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'));

    }

This is my code in Controller. 这是我在Controller中的代码。 I am using a starter bundle available on GitHub. 我正在使用GitHub上提供的入门套件。

I created this model for this controller 我为这个控制器创建了这个模型

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

Problem is it is not taking the results where title contains "Lorem ipsum". 问题是它没有取得标题包含“Lorem ipsum”的结果。 It just prints all the values from the table. 它只打印表中的所有值。

How can i implement this to get only the values that contain my Tag/Keyword. 如何实现此功能以仅获取包含我的标记/关键字的值。 I am doing this to add search option to the laravel site 我这样做是为了在laravel网站上添加搜索选项

Why not create a scope for this? 为什么不为此创建范围? Have you read scopes docs ? 你读过范围文档吗? Here is an example how would I have achieved that: 这是一个例子,我将如何实现这一目标:

The scope: 范围:

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

And modification to your action: 并修改您的行动:

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'));

}

Try this... 尝试这个...

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

Or something along these lines... 或者沿着这些方向......

$search being your input $ search是你的输入

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

EDIT 编辑

What about this? 那这个呢?

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

I think it was an issue with the Laravel Eager loading Constraints implementations: 我认为这是Laravel Eager加载Constraints实现的一个问题:

For ref:- 对于参考: -

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM