【问题标题】:Storing and Fetching more than one table from a Single Model从单个模型中存储和获取多个表
【发布时间】:2015-02-21 08:02:48
【问题描述】:

这是我的模型

<?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

如果不是这样,是否有可能我该怎么做,以便我应该能够从同一模型中获取详细信息。

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

【问题讨论】:

  • vehicleroute 听起来很像我的关系。在这种情况下,您最好创建一个模型。我的意思是这不是很多工作,你基本上只需要添加另一个类。还是我错了?
  • 是的,我应该创建另一个模型,但是扩展另一个类不是更好的主意吗?
  • 我不这么认为。 vehicleroute 没有任何共享功能吗?
  • 抱歉回复晚了,是的,他们没有任何共享功能。是的,现在我明白了
  • 好的。无论如何我都会写一个答案;)

标签: php laravel laravel-4 model


【解决方案1】:

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

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

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

车辆模型

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

路线模型

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

【讨论】:

    【解决方案2】:

    为什么不扩展 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';
    }
    ?>
    

    【讨论】:

    • 谢谢,但我需要检查我是否扩展了课程,我是否能够获得像 $table 这样的详细信息
    猜你喜欢
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2020-05-18
    • 1970-01-01
    • 2020-08-21
    相关资源
    最近更新 更多