laravel - 与雄辩的关系
问题描述
我正在使用laravel 6.16.0
并且有两个迁移:
人
Schema::create('persons', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('full_name')->nullable($value = true);
$table->date('date_of_birth')->nullable($value = true);
$table->string('phone')->nullable($value = true);
$table->string('office')->nullable($value = true);
$table->timestamps();
});
参议员属性
Schema::create('senator_attributes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('persons_id')->default('999999')->nullable($value = true);
$table->string('party')->nullable($value = true);
// ...
$table->timestamps();
});
我的模型如下所示:
class Person extends Model
{
protected $table = 'persons';
protected $guarded = ['id'];
}
class SenatorAttributes extends Model
{
protected $table = 'senator_attributes';
protected $guarded = ['id'];
public function person()
{
return $this->belongsTo(Person::class, 'persons_id');
}
}
我想知道,如何查询所有人员并为每个人获取他们的属性?
感谢您的回复!
解决方案
对于非常直接的解决方案,您可以直接执行以下操作:
首先,您需要在模型中添加SenatorAttributes
模型Person
。您可以这样做:
class Person extends Model
{
protected $table = 'persons';
protected $guarded = ['id'];
public function senator_attributes()
{
return $this->hasMany(SenatorAttributes::class, 'persons_id'); // or you can use hasOne if person model is supposed to only have one single senator attribute.
}
}
现在为每个人加载参议员属性。
Solution 1
,急切(早期/绝望)加载:
$persons = Person::with('senator_attributes')->get();
Solution 2
,按需加载:
$persons = Person::all();
foreach($persons as $person) {
$senator_attribures = $person->senator_attributes;
// write your logic here...
}
只要您不在运行时加载所有行,解决方案 1 就可以。如果您计划加载数百/数千个模型,请考虑将解决方案分块并使用急切加载。
在此处了解有关 Laravel Eloquent 关系的更多信息。
现在,如果您对最佳实践感兴趣,请阅读以下内容。
我不想听起来很爱管闲事,但我个人在从事任何项目时都遵循以下基本规则。
表名应始终为复数形式,模型名称应始终为单数形式。例如,
persons
表将有Person
模型。外键应始终位于
singular form of referenced table
+中referenced column of the referenced table
。例如,如果您希望添加person
对表的引用senator_attributes
,则应将person_id
列添加到senator_attributes
表中。
事实上,Laravel 支持这种命名约定,最重要的是,您可以节省时间并保持团队和项目之间的一致性和实践。
推荐阅读
- python - 在 python 中使用生成器函数访问输出的问题
- r - 根据 R 中日期时间的条件连接多列
- apache-camel - 如何使用聚合器选项,例如完成大小、完成超时和拆分聚合
- html - 无法打开索引页面
- laravel - 在 laravel 中创建控制器时有没有办法调用模型?
- css - 仅使用 CSS 背景设计列
- python-3.x - 在 python 3 中使用 subprocess.check_call 运行 Oracle DBCA
- c# - 如何使用 Microsoft.Identity.Web 对 Azure.Storage.Blobs 进行授权?
- sql-server - Scriptella - SQLServerException:为更新生成了结果集
- excel - 如何创建一个仅自动从第二个列表中提取唯一实例的列表 - 即使第二个列表已更改?