douyuan1049 2014-11-24 20:04
浏览 50
已采纳

无法让Laravel的关系工作,新手

I started learning 2 days ago. I have made a simple user login and blog posting system.

Here is my code that will fetch all the blog posts, but should also join the tables together

public function index()
{
    $blog = new Blog;

    $view = View::make('blogs.index');
    $view->posts = $blog->get()->user;

    return $view;
}

Is this right? Looking at documentation and searching, it seems to be right but I keep getting the following error:

Undefined property: Illuminate\Database\Eloquent\Collection::$user

My blog table is structed like this: enter image description here

And user table like so enter image description here

Blog Model

class Blog extends Eloquent {

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

User Model

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');


    public function blog()
    {
        return $this->hasMany('Blog', 'id', 'user_id');
    }
}
  • 写回答

2条回答 默认 最新

  • dongnuochen9449 2014-11-24 20:19
    关注

    In your index() function try this

    public function index()
    {
         $posts = Blog::all();
    
         return View::make('blogs.index', array('posts' => $posts));
    }
    

    And then in blogs.index you can access the relationship by (blade)

    {{ $posts->user->id }}, {{ $posts->user->email }} or any column in your DB

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C# P/Invoke的效率问题
  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理