当前位置:Gxlcms > PHP教程 > laravelEloquentORM——关联

laravelEloquentORM——关联

时间:2021-07-01 10:21:17 帮助过:13人阅读

表结构

  1. <code>posts
  2. id - integer
  3. title - string
  4. body - text
  5. comments
  6. id - integer
  7. post_id - integer
  8. user_id - integer
  9. body - text
  10. users
  11. id - integer
  12. name - string
  13. phone - integer
  14. sex - integer
  15. comment_likes
  16. id - integer
  17. comment_id - integer
  18. user_id - integer</code>

使用 laravel Eloquent ORM

  1. <code><!--?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Posts extends Model
  5. {
  6. /**
  7. * @var string
  8. */
  9. protected $table = 'posts';
  10. public function comments()
  11. {
  12. return $this--->belongsTo('App\Comments', 'post_id', 'id');
  13. }
  14. }</code>

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

回复内容:

表结构

  1. <code>posts
  2. id - integer
  3. title - string
  4. body - text
  5. comments
  6. id - integer
  7. post_id - integer
  8. user_id - integer
  9. body - text
  10. users
  11. id - integer
  12. name - string
  13. phone - integer
  14. sex - integer
  15. comment_likes
  16. id - integer
  17. comment_id - integer
  18. user_id - integer</code>

使用 laravel Eloquent ORM

  1. <code><!--?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Posts extends Model
  5. {
  6. /**
  7. * @var string
  8. */
  9. protected $table = 'posts';
  10. public function comments()
  11. {
  12. return $this--->belongsTo('App\Comments', 'post_id', 'id');
  13. }
  14. }</code>

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

Comment.php

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

读取时 with

  1. <code>$posts = Post::where(....)->with(['comments' => function($query) {
  2. $query->with('user');
  3. }])->get();
  4. foreach($posts $post)
  5. foreach($post->comments as $comment)
  6. echo $comments->user->name;</code>

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


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

  1. <code>$posts = Post::find(1);
  2. foreach ($posts->comments as $comment)
  3. echo $comment->user->name;</code>

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

人气教程排行