2016-05-28 13 views
1

私はこの質問に関連して調査しましたが、私の状況では動作しませんでした。私は最初のフレームワークを学ぶためにLaravel 5.2を勉強しています。しかし、私はこの問題を "Eager Loading"を使っているチュートリアルで遭遇しました。Laravel 5.2のEager Loadingが動作していません

私はカードモデルが必要なのかはわからないが、私はそれらを追加しましたことを確認します。

私は何をしようとしていますか? メモに関連付けられているユーザーを表示したいとします。


これらは私のコードやファイル

CardsController.php

public function show(Card $card) 
{ 

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

} 

TABLESです:

ユーザー

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

MODELS: namespaceuse空白になっている他のモデル

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

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

Note.php

User.php

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class User extends Model 
{ 
    public function User() 
    { 
     return $this->belongsTo(Note::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を短縮欠落コードだってを見れば、私に教えてください。

答えて

0

解決策を考えながら突然ポップアップします。これは私の問題を解決しました。私はちょうどUser.phpモデルの下のコードを追加しました。そしてそれは魔法のように働いた。

public function User() 
    { 
     return $this->belongsTo(Note::class); 
    } 
関連する問題