英文:
Relation in one table
问题
I have table books (model Book
) with columns: id
, group_key
, content
. And I have 3 rows in this table:
1 | 1 | content1
2 | 1 | content2
3 | 1 | content3;
In model I have relation
public function allGroupItems()
{
return $this->hasMany(self::class, 'group_key');
}
I get first item in table and try to use relation allGroupItems
to get all rows in table with the same group_key
as in first item.
$book = Book::find(1);
dd($book->allGroupItems); // 3 rows
And I succeed. I'm getting 3 rows as expected. But if I try to do the same with second or third row, I've got empty array as result:
$book = Book::find(2);
dd($book->allGroupItems); // empty array
I expect to get the same 3 rows. I don't understand why I am getting an empty array. What's wrong?
Laravel 9.52.7, php 8.2.1
英文:
I have table books (model Book
) with columns: id
, group_key
, content
. And I have 3 rows in this table:
1 | 1 | content1
2 | 1 | content2
3 | 1 | content3;
In model I have relation
public function allGroupItems()
{
return $this->hasMany(self::class, 'group_key');
}
I get first item in table and try to use relation allGroupItems
to get all rows in table with the same group_key
as in first item.
$book = Book::find(1);
dd($book->allGroupItems); // 3 rows
And I succeed. I'm getting 3 rows as expected. But if I try to do the same with second or third row, I'v got empty array as result:
$book = Book::find(2);
dd($book->allGroupItems); // empty array
I expect to get the same 3 rows. I don't understand why I am getting an empty array. What's wrong?
Laravel 9.52.7, php 8.2.1
答案1
得分: 1
public function allGroupItems(): HasMany
{
return $this->hasMany(self::class, 'group_key', 'group_key');
}
英文:
public function allGroupItems(): HasMany
{
return $this->hasMany(self::class, 'group_key', 'group_key');
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论