laravel Eloquent ORM —— 关联

表结构

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

使用 laravel Eloquent ORM

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

希望 在查询 posts 的 留言信息的时候, 一起通过 commentsuser_id 的查询到 users 所有的信息

阅读 3k
1 个回答

Comment.php

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

读取时 with

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

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

一般是这么弄的,使用with比较省性能,


如果你对性能不在乎,可以如下这么弄。不过我会给你打0分。不要学下面

$posts = Post::find(1);
foreach ($posts->comments as $comment)
    echo $comment->user->name;

为什么?看看我写的ORM的教程中对使用with的区别
http://www.load-page.com/base...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题