0

我有两个表用户和文章表之间的关系是

模型:

class Article extends Eloquent {

  public static $table = 'article';

  public function User()
    {
    return $this->has_one('user', 'id');
    }

class User extends Eloquent {

  public static $table = 'user';

  public function Article()
    {
       return $this->belongs_to('article', 'id_user');
    }

我想直接在文章视图上从用户获取名称值,但不能使用错误尝试获取非对象的属性

我的控制器:

public function action_index()
    {

    $Article = Article::order_by('id')->paginate(10);

    return View::make('article.index')->with('$articles', $Article);
    }

我的观点:

@foreach ($articles->results as $Arti)
      <tr>
       <td>{{$Arti->id}}</td>
       <td>{{$Arti->tag}}</td>
       <td>{{$Arti->user->name }}</td>  <------ ERROR
       <td>{{$Arti->content}}</td>
       <td>{{$Arti->date}}</td>
       <td>
4

1 回答 1

2

看看下面,有几件事与你的不同......

  1. 文章 belongs_to 用户(不是 has_one)
  2. 用户has_many文章(不是belongs_to)
  3. 您的关系应以小写形式命名,has_many 的复数形式(即articlesuser
  4. 您的关系主题应该是类名(即ArticleUser
  5. 外键应该是名字relationship_id,即user_id
  6. 添加::with()到您的查询以渴望加载关系
  7. 当您分页时,您需要->results在您的视图中访问

class Article extends Eloquent {

    // 3: lowercase 'user'
    public function user()
    {
        // 1: Article belongs to User
        // 4: class name 'User'
        // 5: Foreign key on article table is user_id
        return $this->belongs_to('User');
    }

}

// models/user.php

class User extends Eloquent {

    // 3: lowercase plural 'articles'
    public function articles()
    {
        // 2: User has many Articles
        // 4: class name 'Article'
        return $this->has_many('Article');
    }

}

// controllers/articles.php

class Article_Controller extends Base_Controller {

    public $restful = true;

    public function get_index()
    {
        // 6: Eager load the user relationship, ::with('user')
        $articles = Article::with('user')->order_by('id')->paginate(10);
        return View::make('articles.index', compact('articles'));
    }

}

// views/articles/index.blade.php
// 7: access $articles->results from the paginator

@foreach ($articles->results as $article)

    <h1>{{ $article->title }}</h1>
    <p>By {{ $article->user->name }}</p>

@endforeach

{{ $articles->links() }}
于 2013-04-12T14:12:25.477 回答