Home >Backend Development >PHP Tutorial >How to write this related query in laravel?

How to write this related query in laravel?

WBOY
WBOYOriginal
2016-07-06 13:53:55944browse

How to write this related query in laravel?

The relationship is as follows:

<code>users表->articles表 ,一对多关系。
categories表->articles表,一对多关系。
</code>

Query:

<code>    public function index()
    {
        $user=\Auth::user();

        //1、查询当前登录用户的文章.
        //2、文章对应的类别.
        //用的下面这样一条语句:
        $articles = $user->articles->with('category');

        return view('index',  compact('articles'));
    }</code>

Error report:
How to write this related query in laravel?

Question:
How should I write the query statement in the index() method?

Reply content:

How to write this related query in laravel?

The relationship is as follows:

<code>users表->articles表 ,一对多关系。
categories表->articles表,一对多关系。
</code>

Query:

<code>    public function index()
    {
        $user=\Auth::user();

        //1、查询当前登录用户的文章.
        //2、文章对应的类别.
        //用的下面这样一条语句:
        $articles = $user->articles->with('category');

        return view('index',  compact('articles'));
    }</code>

Error report:
How to write this related query in laravel?

Question:
How should I write the query statement in the index() method?

Change it to this, change article to a method, so that what is returned is not the result, but the query builder:
$articles = $user->articles()->with('category')->get();

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