您好我下面的教程,我得到了有關顯示所謂listing.blade.php顯示對象,具有雄辯
@extends('layouts.default')
@section('content')
@foreach($posts as $post)
<h1>{{{$post->title}}} By {{{$post->user->email }}}</h1>
@endforeach
@stop
在我看來,一個對象的一個問題但是代碼不工作,因爲我得到了錯誤:
Trying to get property of non-object.
我得到這個錯誤的原因是因爲變量$ post是一個數組。
所以這個代碼工作:
<h1>{{{$post->title}}} By {{{$post->user['email'] }}}</h1>
但是我不想用我上面的代碼符號。我想用這樣的:
<h1>{{{$post->title}}} By {{{$post->user->email }}}</h1>
這裏是我的控制器稱爲PostController.php代碼:
<?php
class PostController extends BaseController {
public function listing(){
$posts = Post::all();
return View::make('post/listing', compact('posts'));
}
}
這裏是我的模型的代碼中調用post.php中:
<?php
class Post extends \Eloquent {
/*this holds all the fields that you can actually sit through
mass assignment */
protected $fillable = ['title', 'body'];
//we set a field 'user_id' that we don't want to be set through mass assignment.
// protected $guarded = ['user_id'];
public function user(){
return $this->belongsTo('User');
}
}
此處還有我的模型的代碼,名爲User.php(因爲它與Post.php有關係):
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
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 posts(){
return $this->hasMany('Post');
}
}
有人能幫我解決我的問題嗎?
它應該作爲一個對象工作。 – 2014-09-21 19:59:03
是的,我知道但不是因爲某種原因。我真的在說實話。如果你想的話,我可以記錄下自己在瀏覽器上顯示這段代碼和輸出。 – superkytoz 2014-09-21 20:03:37
我猜想其中'posts'沒有相關的'user' – 2014-09-21 20:08:14