【问题标题】:Relations Laravel 4 from 3 tables关系 Laravel 4 来自 3 个表
【发布时间】:2014-01-03 20:02:30
【问题描述】:

我开始学习 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

content_post

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();

我哪里出错了?

【问题讨论】:

    标签: php mysql orm laravel-4


    【解决方案1】:

    你应该这样声明关系:

    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);
    

    【讨论】:

    • 此外,如果您坚持一些规则,例如为模型(用户、帖子、内容)使用单数名称,则会容易得多。
    • 谢谢你的回复,你已经很清楚了。但是当我尝试使用 foreach 显示结果时,它向我展示了尝试获取非对象的属性可能是什么问题?#
    • 可能您正在尝试迭代 Builder 对象。注意 $user->posts() 不返回集合。为了遍历用户相关的帖子,您可以通过魔术方法 __get() 访问它们。类似于:foreach($user->posts as $post){}
    • 好的!谢谢!抱歉这个愚蠢的问题,但是为什么即使我们设置了关系 $user->posts() 也不返回集合?
    • 主要是因为它用于查询构建目的。 Builder 对象允许您实现更复杂的逻辑(过滤、排序等)。例如你可以这样写: $user->posts()->where('created_at', 'get();
    猜你喜欢
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多