拉拉维尔急切的装载

时间:2016-05-22 15:17:40

标签: php laravel

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use DB;
use App\Card;


class CardController extends Controller
{
    //
    public function index()
    {
        $cards = Card::all();
        return view('cards.index',compact('cards'));

    }

    public function show(Card $card)
    {
        $card->load('notes.user');

        return $card;

       // return view('cards.show',compact('card'));
    }
}

我是laravel的新手,并继续阅读laracast介绍教程。我试图加载与我的数据库中的笔记相关联的用户,但我不断收到错误,调用未定义的方法Illuminate \ Database \ Query \ Builder :: user()&#39;。我不知道问题是什么,因为我刚开始学习。 以下是卡类

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Card extends Model
{

    public function notes()
    {
        return $this->hasMany(Note::class);
    }

}
下面的

是Notes类     

namespace App;

use Illuminate\Database\Eloquent\Model;

class Note extends Model
{
    protected $fillable = ['body'];

    public function card()
    {
        return $this->belongsTo(Card::class);
    }
}

以下是用户类

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

1 个答案:

答案 0 :(得分:0)

我只需要在Notes类中为用户添加关系,如下所示。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Note extends Model
{
    protected $fillable = ['body'];

    public function card()
    {
        return $this->belongsTo(Card::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}