从视图获取值


Get value from view

我有两个表User &文章表之间的关系

模型:

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>

看一下下面,有一些东西和你的不一样…

  1. Article belongs_to User (not has_one)
  2. User has_many Article (not 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() }}