php - 此集合实例上不存在属性 [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();
解决方案
您实际上是在尝试从整数值中获取文章,因为这是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 循环。
推荐阅读
- reactjs - 如何内联编辑反应虚拟化表格单元格?
- node.js - nodejs sqlite3中的通配符
- java - Hibernate PreInsertEventListener 修改的字段在 Spring Boot Repository POST 响应 JSON 中显示为 null
- python-3.x - 文本冒险的 if 语句,需要在继续之前检查元素列表
- pandas - 将列添加到日期时间驱动的 Groupby 函数
- java - 如何返回结果集?
- java - Gradle Jar 类型任务不会从 src/main 打包 .class 文件
- r - 如何将两个十分位 bin 连续变量?
- reactjs - 如何在本机反应中使用嵌套的 json 请求?
- r - R:如何:ggbarplot 到实际值