Laravel 中 table 关系的概念
Concept of table relations in Laravel
我有两个 table:
Cards
Notes
每张卡片有多个笔记。所以他们之间有这样的关系:
class Card extends Model {
public function notes ()
{
return $this->hasMany(Note::class);
}
}
好的,没问题。
现在我需要理解这两行的概念:
$card()->$notes()->first();
和
$card()->$notes->first();
它们有什么区别?正如您在第一个中看到的 $note()
是一个函数,而在第二个中 $note
不是一个函数。 PHP 将如何翻译?
第一个指向card
table,第二个指向notes
table,对吧?或者是什么?不管怎样,我一直坚持理解tham的概念。
我不知道你代码中 $notes
之前的 $
,但如果你想说这样的话。
1- $card->notes()->first();
2- $card->notes->first();
在第 1 行的代码中,首先您有一个 $card
模型,然后您想访问与该 $card
相关的所有 notes()
,并且由于添加 [=16] =] 在 notes
之后,您只需在笔记上调用 query builder
,表明您可以在此之后执行任何其他数据库查询功能,例如 where, orderBy, groupBy, ...
和任何其他对数据库的复杂查询。
但在第二个中,您实际上可以访问 collection
个与 $card
相关的注释,我们可以说您得到 所有相关注释 并将其设置为 laravel 集合,您将无法再对 notes
.
执行数据库查询
Note: because laravel collections have some methods like where(), groupBy(), whereIn(), sort(), ...
you can use them on the second one, but in that case you perform those methods on collections and not database, you already get all results from database
我有两个 table:
Cards
Notes
每张卡片有多个笔记。所以他们之间有这样的关系:
class Card extends Model {
public function notes ()
{
return $this->hasMany(Note::class);
}
}
好的,没问题。
现在我需要理解这两行的概念:
$card()->$notes()->first();
和
$card()->$notes->first();
它们有什么区别?正如您在第一个中看到的 $note()
是一个函数,而在第二个中 $note
不是一个函数。 PHP 将如何翻译?
第一个指向card
table,第二个指向notes
table,对吧?或者是什么?不管怎样,我一直坚持理解tham的概念。
我不知道你代码中 $notes
之前的 $
,但如果你想说这样的话。
1- $card->notes()->first();
2- $card->notes->first();
在第 1 行的代码中,首先您有一个 $card
模型,然后您想访问与该 $card
相关的所有 notes()
,并且由于添加 [=16] =] 在 notes
之后,您只需在笔记上调用 query builder
,表明您可以在此之后执行任何其他数据库查询功能,例如 where, orderBy, groupBy, ...
和任何其他对数据库的复杂查询。
但在第二个中,您实际上可以访问 collection
个与 $card
相关的注释,我们可以说您得到 所有相关注释 并将其设置为 laravel 集合,您将无法再对 notes
.
Note: because laravel collections have some methods like
where(), groupBy(), whereIn(), sort(), ...
you can use them on the second one, but in that case you perform those methods on collections and not database,you already get all results from database