用Eloquent显示对象

时间:2014-09-21 19:42:21

标签: php mysql laravel eloquent blade

您好我正在关注一个教程,我得到一个关于在我的视图中显示一个名为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');
    }
}

有人可以帮我解答一下我的问题吗?

1 个答案:

答案 0 :(得分:1)

我一直在做的是使用三元运算符:

{{{ $post->title ?: 'No Title' }}}

相当于:

isset($post->title) ? $post->title : 'No Title';

通过这种方式,您可以添加一层安全保护,以防错过任何内容。