Home >Backend Development >PHP Tutorial >laravel Eloquent ORM - Relevance

laravel Eloquent ORM - Relevance

WBOY
WBOYOriginal
2016-10-11 14:23:371215browse

Table structure

<code>posts
    id - integer
    title - string
    body - text

comments
    id - integer
    post_id - integer
    user_id - integer
    body - text
users
    id - integer
    name - string
    phone - integer
    sex - integer
    
comment_likes
    id - integer
    comment_id - integer
    user_id - integer</code>

Using laravel Eloquent ORM

<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model
{
     /**
     * @var string
     */
    protected $table = 'posts';

    public function comments()
    {
        return $this->belongsTo('App\Comments', 'post_id', 'id');
    }
}</code>

I hope that when querying the message information of posts, we can query all the information of users through the user_id of comments

Reply content:

Table structure

<code>posts
    id - integer
    title - string
    body - text

comments
    id - integer
    post_id - integer
    user_id - integer
    body - text
users
    id - integer
    name - string
    phone - integer
    sex - integer
    
comment_likes
    id - integer
    comment_id - integer
    user_id - integer</code>
Using

laravel Eloquent ORM

<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model
{
     /**
     * @var string
     */
    protected $table = 'posts';

    public function comments()
    {
        return $this->belongsTo('App\Comments', 'post_id', 'id');
    }
}</code>
I hope that when querying the message information of

posts, we can query all the information of users through the user_id of comments

Comment.php

<code>class Comment extends Model {
    public function user () {
        return $this->hasOne('App\User', 'id', 'user_id');
    }
}</code>

When reading with

<code>$posts = Post::where(....)->with(['comments' => function($query) {
    $query->with('user');
}])->get();

foreach($posts $post)
    foreach($post->comments as $comment)
        echo $comments->user->name;</code>

This is usually how it is done. Using with saves performance,

If you don’t care about performance, you can do it as follows. But I will give you 0 points.
Don’t learn from the following

<code>$posts = Post::find(1);
foreach ($posts->comments as $comment)
    echo $comment->user->name;</code>
Why? Take a look at the difference in using with in the ORM tutorial I wrote

http://www.load-page.com/base...

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