php - 来自 3 个表的关系 Laravel 4

标签 php mysql orm laravel-4

我开始学习 laravel 4 但我还很远,我已经看过 ORM 和关系所以我有以下问题:

我有 3 种类型的表:users、posts、content_post,我希望所有关于用户的帖子和内容都具有类似的结果。

用户表

id | userame | name |
 1    Ellie    Elen
 2    Pol      Paul

帖子表

id | id_poster |
 1      1
 2      1
 3      2

内容发布

id | id_post | text | link | video | photo
 1      1      hey    NULL   NULL    tree.png
 2      2      woo    http   NULL    NULL
 3      3      Hi     NULL   NULL    NULL

PHP

    class User Extends Eloquent {

     function posts() {
         return $this->belongsToMany('posts','id_poster');
     }

    }

    class Posts Extends Eloquent {

     function user() {
         return $this->HasOne('users');
     }

     function content() {
       return $this->HasOne('content_post','id_post');
     }

    }

  class Content Extends Eloquent {

     function posts() {
         return $this->HasOne('posts');
     }

  }

    ?>

然后我会像这样去获取结果,但它没有显示任何内容

$user = new User;
$user = $user->find(1)->posts();

我在哪里做错了?

最佳答案

你应该这样声明关系:

class User Extends Eloquent {

    function posts() {
        return $this->hasMany('Posts','id_poster'); /* Note that 'Posts' is model name - not table */
    }

}

class Posts Extends Eloquent {

    function user() {
        return $this->belongsTo('User', 'id_poster');
    }

    function content() {
        return $this->hasOne('Content','id_post');
    }

}

class Content Extends Eloquent {

   function posts() {
       return $this->belongsTo('Posts', 'id_post');
   }
}

在您可以尝试通过帖子请求用户之后:

$user = new User();
$user = $user->with('posts.content')->find(1);

关于php - 来自 3 个表的关系 Laravel 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20610773/

相关文章:

php - 在存储过程之外提交事务

php - 选择多个选项 sql 和 php

mysql - 如何访问和查看 Liferay

php - 使用 PHP 管理大量数据的最快方法? (每个客户请求的数据总共可达 100mb)

java - Hibernate + MySQL简单批量插入极慢

php - 是否可以在 PHP 中进行方法调用?

php - 无法从 USB 创建数据库转储

php - MySQL 行数总是返回 false

java - hibernate nextval 获取 id

java - Hibernate 单元测试 - 重置架构