0

我正在尝试通过使用 Laravel Eloquent HasMany(反向)关系来获取数据,但我无法访问。每当我尝试时,它都会显示Trying to get property 'name' of non-object

我有两个模型。类别文章类别有很多文章。以下是模型:

类别模型

protected $fillable = [
    'user_id', 'name', 
]; 

public function articles()
{
    return $this->hasMany('App\Models\Article');
}

文章模型

protected $fillable = [
    'user_id', 'headline', 'summary', 'body', 'status', 'cover_image', 'image_caption', 'image_credit', 'cover_video', 'video_caption', 'video_credit', 'category', 'meta', 'tags',
]; 

public function category()
{
    return $this->belongsTo('App\Models\Category','category');
}

文章控制器

public function pendingposts()
{
    $user = Auth::user();
    $articles = Article::all();
return view('admin.article.pending-posts')->with(['user' => $user, 'articles' => $articles]);
}

查看刀片(admin.article.pending-posts)

@foreach($articles->where('status', 'submitted')->sortByDesc('updated_at') as $article)
<tr>
<td >{{ $article->headline }}</td>
<td>{{ $article->category->name }} </td>
</tr>
@endforeach

在刀片中,我无法通过 eloquent BelongsTo 功能访问类别,也没有得到消息背后的原因:

ErrorException (E_ERROR) 试图获取非对象的属性“名称”(查看:C:\xampp\htdocs\joliadmin\resources\views\admin\article\pending-posts.blade.php)

4

2 回答 2

0

你应该试试这个:

    public function pendingposts()
{
    $user = Auth::user();
    $articles = Article::with('category')
        ->where('status', 'submitted')
        ->sortByDesc('updated_at')
        ->get(); 

    return view('admin.article.pending-posts')->with(compact('user', 'articles'));
}

@foreach($articles as $article)
    <tr>
    <td>{{ $article->headline }}</td>
    <td>{{ $article->category->name }} </td>
    </tr>
@endforeach

更新的答案

类别模型

protected $fillable = [
    'user_id', 'name', 
]; 

public function article()
{
    return $this->hasMany('App\Models\Article');
}
于 2019-01-10T11:36:31.700 回答
0

它在“category_id”中更改“文章”表“类别”列后起作用。感谢您的帮助。

于 2019-01-14T07:29:13.620 回答