Home >Backend Development >PHP Tutorial >laravel Eloquent ORM - Relevance
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
<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
<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.
<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