从单个模型存储和获取多个表

时间:2014-12-23 07:33:59

标签: php laravel laravel-4 model

这是我的模特

<?php
class VehicleModel extends Eloquent 
{
    protected $primaryKey = 'AutoID';  # to change the primary key else laravel will consider id as primary key
    protected $table = 'vehicle';
}

使用此我可以获取

$vehiclelist = VehicleModel ::all();

但是我需要从同一个模型中获取另一个表

是否有可能拥有这样的东西

<?php
class VehicleModel extends Eloquent 
{
 protected $primaryKey = 'AutoID';  # to change the primary key else laravel will consider id as primary key
 protected $table = 'vehicle';
 protected $secondtable = 'route';
}

应该可以通过

访问
$routelist= Detail::make(VehicleModel ::$secondtable );// This is the thing i am doing wrong

是否有可能以这种方式,如果不能如何做到这一点,以便我应该能够从同一模型中获取细节。

注意: 我无法为每个表创建单独的模型,因为我需要为每个表单获取许多(不同的)表

2 个答案:

答案 0 :(得分:0)

为什么不扩展VehicleModel类? 我认为除了延伸之外没有办法。

<?php
class VehicleModel extends Eloquent 
{
    protected $primaryKey = 'AutoID';  # to change the primary key else laravel will consider id as primary key
    protected $table = 'vehicle';
}

class RouteModel extends VehicleModel
{
    protected $table = 'route';
}

class StuffModel extends VehicleModel
{
    protected $table = 'stuff';
}
?>

答案 1 :(得分:0)

如果你有多个表不同的东西(不是多表继承),你真的应该为每个表创建一个模型。这不是那么多工作,但会让事情变得更容易。

对于以下示例,我们假设一辆车可以有多条路线。在数据库中,VehicleID表中的route引用了AutoID表中的vehicle

然后你可以在你的模型中添加这两个关系

VehicleModel

public function routes(){
    return $this->hasMany('RouteModel', 'VehicleID');
}

RouteModel

public function vehicle(){
    return $this->belongsTo('VehicleModel', 'VehicleID');
}

现在这里有一些如何使用它的例子:

$vehicle = VehicleModel::find(1);
$routesOfVehicle1 = $vehicle->routes;

$route = RouteModel::find(1);
$vehicleOfRoute1 = $route->vehicle;

$allVehiclesIncludingTheirRoutes = VehicleModel::with('routes')->get();

有关详情,请参阅Laravel Docs on Relations