表结构
<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>使用 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>希望 在查询 posts 的 留言信息的时候, 一起通过 comments 的 user_id 的查询到 users 所有的信息
表结构
<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>使用 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>希望 在查询 posts 的 留言信息的时候, 一起通过 comments 的 user_id 的查询到 users 所有的信息
Comment.php
<code>class Comment extends Model {
public function user () {
return $this->hasOne('App\User', 'id', 'user_id');
}
}</code>读取时 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>一般是这么弄的,使用with比较省性能,
如果你对性能不在乎,可以如下这么弄。不过我会给你打0分。不要学下面
<code>$posts = Post::find(1);
foreach ($posts->comments as $comment)
echo $comment->user->name;</code>为什么?看看我写的ORM的教程中对使用with的区别
http://www.load-page.com/base...
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号