Laravel:如何检索从 parent 模型扩展的 child 模型的所有实例?

Laravel: how to retrieve all instances of child models which extend from parent model?

我们有不同模型的记录,但它们是从相同的 parent 模型扩展而来的。

我有一个页面,我想在其中显示 parent 所有记录的列表。如何检索所有记录作为 parent 模型?

示例:

class LivingBeing extends Model{
    public function isAlive(){
         return $this->is_alive; //boolean
    }
}

class Human extends LivingBeing{
    use hasSpine; //eloquent handling for spine data
    $table = 'humans';
}

class Cat extends LivingBeing{
    use hasSpine; //eloquent handling for spine data
    $table = 'cats';
}

class Squid extends LivingBeing{
    use hasTentacles; //eloquent handling for tentacle data
    $table = 'squids';
}

我想检索可变形的 eloquent 数据集合,例如:

App\Models\LivingBeing //Human 1
App\Models\LivingBeing //Cat 1
App\Models\LivingBeing //Cat 2
App\Models\LivingBeing //Squid 1

有没有办法查询所有类似于..的LivingBeings模型?

LivingBeing::all()

我只用生物的东西举例。我们的系统实现了与文档相同的功能。 :)

这取决于您在数据库中存储模型的方式。

第一种方法:物种作为一个领域

如果你有一个 table 用于 living_beings 并且它有一个列名 species

您可以通过以下方式访问所有内容:

LivingBeing::all();

并且在每个模型中您都必须实现范围:

public static function boot()
     {
         parent::boot();
         static::addGlobalScope("specie", function ($query) {
             //specify type in child class
             //$query->where("specie_type", "cat");
             
             //specify in child if you have a species table
             //$query->where("specie_id", 2);
             
             //i think you can do it in parent once but i am not sure
             $query->where("specie", this::class.'');
         });
     }

第二种方法:每个物种都有 table 生物 table

每个物种都有一个字段名称living_being_id

访问每个物种

Cat::all();

或通过生物:

    LivingBeing::select("*")::join("cats","cats.living_being_id","living_beings.id")->get();

第三种方法:(不推荐 - 未标准化数据)每个物种都有一个 table 本身。

要获取所有物种,您必须合并查询:

Cat::all()->union(Dog::all());

结论

最佳方法#1