【问题标题】:Eager Loading in Laravel 5.2 is not workingLaravel 5.2 中的急切加载不起作用
【发布时间】:2016-05-28 16:09:10
【问题描述】:

我研究了与此问题相关的内容,但没有针对我的情况进行研究。我现在正在学习 Laravel 5.2 来学习我的第一个框架。但是我在使用“Eager Loading”的教程中遇到了这个问题。

我不确定是否需要 Card ModelTable,但只是为了确保我添加了它们。

我要做什么? 我想显示与笔记关联的用户。


这些是我的代码和文件

CardsController.php

public function show(Card $card)
{

    return $card->notes[0]->user;

}

表格:

用户

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('username')->unique();
        $table->string('email')->unique();
        $table->string('password');
        $table->timestamps();
    });

备注

Schema::create('notes', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->integer('card_id')->unsigned()->index();
            $table->text('body');
            $table->timestamps();
        });

卡片

Schema::create('cards', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->timestamps();
    });

型号: namespaceuse 与其他空白模型相同

User.php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Note.php

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

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

Card.php

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

    public function addNote(Note $note)
    {
        return $this->notes()->save($note);
    }
}

预期输出:

Expected Output Image

我的输出:

我的输出是空白的。浏览器没有显示任何内容。


如果您看到缺少代码,请告诉我,因为我缩短了 CardsController.php,因为我认为代码很重要。

【问题讨论】:

    标签: php laravel frameworks laravel-5.2 eager-loading


    【解决方案1】:

    一边想着解决办法,一边脑子里突然冒出来。这解决了我的问题。我刚刚在User.php 模型中添加了以下代码。它就像魔术一样工作。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      相关资源
      最近更新 更多