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

问题描述

我有 2 个相互链接的模型:链接和条目。在我的条目表中,我创建了一个名为 link_id 的 foreignId。

入门型号:

class Entry extends Model
{

use HasFactory;

protected $guarded = [];

protected $table = 'entries';

public function link() {
    return $this->belongsTo(Link::class);
}

链接型号:

class Link extends Model

{

use HasFactory;
use Uuids;

protected $guarded = [];

public function user() {
    return $this->belongsTo(User::class);
}

public function entries() {
    return $this->hasMany(Entry::class);
}

当访问者访问该链接时,就会创建一个条目。该链接包含一些值,例如标题等。

现在我还制作了一个管理面板,我可以在其中将数据作为字符串上传到数据库中的“customInput”字段。我只是不知道如何获取该数据,因为当我尝试使用 $link->entries->customInput 时,Laravel 会返回此错误:Property [customInput] does not exist on this collection instance。

我怎样才能解决这个问题?

标签: phplaraveleloquenthas-manybelongs-to

解决方案


$link->entries是一个集合,所以你需要一个循环来从这个集合中获取值:

@foreach($link->entries as $data)
   {{ $data->customInput }}
@endforeach

推荐阅读