Home >Backend Development >PHP Tutorial >laravel的filter()方法的使用

laravel的filter()方法的使用

WBOY
WBOYOriginal
2016-06-06 20:10:322092browse

下面的方法是取出一个用户的所有文章,再把文章分成两组,publishedunpublished,

<code>public function index(Request $request)
{
    $articles = $request->user()->articles()->get();

    $published = $articles->filter(function ($article) {
        return $article->status == 1;
    });

    $unpublished = $article->filter(function ($article) {
        return $article->status == 0;
    });

    return view('user.dashboard.index', compact('published', 'unpublished'));
}</code>

现在,在分组的时候,需要多增加一个过滤条件,比如这个:

<code>$published = $articles->filter(function ($article) {
        return $article->status == 1;
    });</code>

上面的过滤的条件只有1个,就是status == 1,
现在增加一个过滤条件publishing_time <br>那么,增加过滤条件后,语法怎么写呢?

回复内容:

下面的方法是取出一个用户的所有文章,再把文章分成两组,publishedunpublished,

<code>public function index(Request $request)
{
    $articles = $request->user()->articles()->get();

    $published = $articles->filter(function ($article) {
        return $article->status == 1;
    });

    $unpublished = $article->filter(function ($article) {
        return $article->status == 0;
    });

    return view('user.dashboard.index', compact('published', 'unpublished'));
}</code>

现在,在分组的时候,需要多增加一个过滤条件,比如这个:

<code>$published = $articles->filter(function ($article) {
        return $article->status == 1;
    });</code>

上面的过滤的条件只有1个,就是status == 1,
现在增加一个过滤条件publishing_time <br>那么,增加过滤条件后,语法怎么写呢?

第一,和你的问题无关,建议你修改下边这一行:

<code>$articles = $request->user()->articles()->get(); // 改成下边
$articles = $request->user()->articles // 这是动态属性的调用方式,是常规用法</code>

第二,来回答你的问题(你可能把问题想复杂了,其实像下边这样简单):

<code>$published = $articles->filter(function ($article) {
    return $article->status == 1 && $article->publishing_time </code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn