首页 > 解决方案 > 此集合实例上不存在属性 [articles]

问题描述

我的模型中有这段代码,称为标签:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    protected $fillable = [
        'tag'
    ];

    public function articles(){
        return $this->belongsToMany(Article::class);
    }
}

我在我的控制器中使用这个代码

 public function fillter($target){
        $tags = tag::where('id', 3)->count();
        $article = $tags->articles;

        foreach ($article as $article){
            return $article->title;
        }

    }

当我运行代码时,我得到一个异常: Property [articles] does not exist on this collection instance。

但如果我能够运行以下代码:

$tags = tag::where('id', 3)->first();

标签: phplaraveleloquent

解决方案


您实际上是在尝试从整数值中获取文章,因为这是count()函数返回的内容。这行代码返回一个整数:

$tags = tag::where('id', 3)->count(); // For ex: 3

您正尝试在下一行代码中执行此操作:

$article = 3->articles; //Which doesn't exist

通过在此处使用这行代码:

$tags = tag::where('id', 3)->first();

您正在返回一个Tag实例,该实例实际上具有该articles属性。

此外,foreach由于两个原因,您的代码将无法工作:

第一:你不能在你的 foreach 循环中使用相同的变量,它应该是这样的:

foreach($articles as $article)

第二:它将在第一个循环后停止执行,因为您有一个 return 语句:

foreach ($articles as $article){
     return $article->title;
}

最好将$articles变量传递给您的视图,并在那里执行一个 foreach 循环。


推荐阅读