关系在一个表中

huangapple go评论56阅读模式
英文:

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');
}

huangapple
  • 本文由 发表于 2023年5月8日 01:48:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76195427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定