【问题标题】:Cannot get Laravel relationships working, newbie无法让 Laravel 关系正常工作,新手
【发布时间】:2014-11-24 20:04:53
【问题描述】:

我 2 天前开始学习。我做了一个简单的用户登录和博客发布系统。

这是我的代码,它将获取所有博客文章,但也应该将表格连接在一起

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

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

    return $view;
}

这是对的吗?查看文档和搜索,似乎是对的,但我不断收到以下错误:

未定义属性:Illuminate\Database\Eloquent\Collection::$user

我的博客表结构如下:

像这样的用户表

博客模型

class Blog extends Eloquent {

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

用户模型

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

【问题讨论】:

    标签: php join laravel eloquent


    【解决方案1】:

    在你的 index() 函数中试试这个

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

    然后在blogs.index你可以通过(刀片)访问关系

    {{ $posts->user->id }}{{ $posts->user->email }} 或数据库中的任何列

    【讨论】:

    • 你能解释一下它是如何知道总是进行连接的吗?那一点让我感到困惑
    • 我希望我知道它背后的深层技术原因,但无论如何我会尽力而为! Laravel 在其模型中使用 Eloquent。 Eloquent 会自动为您加载您定义的关系,然后您可以使用称为“动态属性”的东西访问这些关系。基本上它真的很聪明!
    【解决方案2】:

    使用$blog = new Blog;,您将开始创建新的博客条目。您真正需要做的是查询博客表并获取用户,这可以通过预加载很容易地完成。试试这个...

    $blogs = Blog::with('users');

    然后,当您创建视图时,您希望使用类似这样的方式在视图中发送博客...with() 方法的第一个参数是您要在视图中赋予变量的名称,以及第二个是要发送的实际变量。

    return View::make('blogs.index')->with('blogs', $blogs);

    【讨论】:

      猜你喜欢
      • 2015-03-22
      • 2014-11-16
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 2019-07-30
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多