首页 > 解决方案 > 与雄辩的关系

问题描述

我正在使用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');
    }
}

我想知道,如何查询所有人员并为每个人获取他们的属性?

感谢您的回复!

标签: laraveleloquent

解决方案


对于非常直接的解决方案,您可以直接执行以下操作:

首先,您需要在模型中添加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 支持这种命名约定,最重要的是,您可以节省时间并保持团队和项目之间的一致性和实践。


推荐阅读