属性[id]在此集合实例上不存在

7 浏览
0 Comments

属性[id]在此集合实例上不存在

我正在尝试创建编辑页面,但是出现了以下错误:

糟糕,好像出了些问题。此集合实例上不存在属性[id]。

我已经完成的工作:

这是我的路由

Route::get('book/edit/{id}', 'BookController@edit')->name('admin.book.edit');
Route::PATCH('book/edit/{id}', 'BookController@update')->name('admin.book.edit');

这是我的控制器

$books = $this->bookModel
        ->join('author', 'author.id', '=', 'book.author_id')
        ->where('book.id', '=', $id)
        ->select('book.*', 'author.name_1 as authorname1')
        ->get();
    return view('backend.book.edit', compact('books', $books));

最后在视图文件的表单部分有以下内容

{{ Form::model($books, ['route' => ['admin.book.edit', $books->id], 'class' => 'form-horizontal', 'role' => 'form', 'method' => 'PATCH']) }}

{{ Form::close() }}

任何帮助将不胜感激。谢谢

0
0 Comments

在使用eloquent关系时,我遇到了类似的错误,错误信息是(Property [id] does not exist on this collection instance)。问题出在我使用了return $this->hasMany(ClassName::class);,但实际关系是一对一的,所以问题的解决方法是使用return $this->hasOne(ClassName::class);

在上面的示例中,第一个代码段将返回对象数组,这将破坏链式eloquent代码中的关系流程,例如$firstChain->middleChain->requiredData。如果middleChain返回的是对象数组,就会出现上述错误,提示属性不存在

在使用eloquent关系时,请务必正确指明关系的类型。感谢Afreed A R,这个方法对我起了作用,我之前在我的模型中返回的是hasMany,而不是hasOne。

0
0 Comments

在上述代码中出现了(Property [id] does not exist on this collection instance)的错误。

错误原因:错误发生在$books->id这一行。在使用get()方法时,返回的是一个集合(collection),而$books是一个集合。因此,需要对集合进行迭代才能获取其属性。

解决方法:将$books集合进行迭代,获取其属性id

修正后的代码如下:

foreach ($books as $book)
    {{ $book->id }}

通过以上修正后的代码,可以解决(Property [id] does not exist on this collection instance)错误。

0
0 Comments

(Property [id] does not exist on this collection instance)错误的原因是在代码中使用了get()方法来获取数据集合,而不是使用first()方法来获取单个记录。解决方法是将get()方法替换为first()方法,并将变量$books替换为$book

具体代码如下:

$book = $this->bookModel
    ->join('author', 'author.id', '=', 'book.author_id')
    ->where('book.id', '=', $id)
    ->select('book.*', 'author.name_1 as authorname1')
    ->first();

请在代码的其他部分中也将$books替换为$book

0