一个模型中的多个表 - Laravel

时间:2014-03-01 19:19:46

标签: php laravel laravel-4 eloquent

我的索引页面在数据库中使用了3个表:

  • index_slider
  • index_feature
  • footer_boxes

我使用一个控制器(IndexController.php)并调用三个模型:

public function index() { 
return View::make('index')
->with('index_slider', IndexSlider::all())
->with('index_feature', IndexFeature::all())
->with('footer_boxes', FooterBoxes::all()); 
}

上面的三个模型需要 :: all()数据,因此它们都设置如下:

class IndexSlider extends Eloquent {
public $table ='index_slider';
}

注意: 每个模型的类名称更改

看到我的索引页需要这3个表,而且我在每个模型中重复语法,那么我应该使用多态关系还是以不同的方式设置它?我读过的ORM应该有每个表的1个模型,但我不禁觉得这对我的情况和其他许多人来说都是愚蠢的。 DRY(不要重复自己)在某种意义上失去意义。

最好的方法是什么,或者我走在正确的轨道上?

1 个答案:

答案 0 :(得分:10)

首先,我应该说每个模型都是针对特定的表格编写的,除非相关,否则不能将三个表格压缩到一个模型中。 See Here

我有两种方法可以让您的代码更干净。 我不会将数据传递给withs链中,而是将其作为make中的第二个参数传递:

public function index() { 
    $data = array(
        'index_slider'  => IndexSlider::all(),
        'index_feature' => IndexFeature::all(),
        'footer_boxes'  => FooterBoxes::all(),
    );

    return View::make('index', $data);
}

将数据作为第二个参数传递。 See here

我会采用另一种方式,如果你的应用程序变得越来越大,这是一个更好的解决方案,就是创建一个服务(另一个模型类,但没有连接到雄辩),当你调用时将返回必要的数据。如果你在多个视图中返回上述数据,我肯定会这样做。

使用服务的示例如下所示:

<?php 
// app/models/services/indexService.php
namespace Services;

use IndexSlider;
use IndexFeature;
use FooterBoxes;

class IndexService
{
    public function indexData()
    {
        $data = array(
            'index_slider'  => IndexSlider::all(),
            'index_feature' => IndexFeature::all(),
            'footer_boxes'  => FooterBoxes::all(),
        );

        return $data;
    }
}

和您的控制人员:

<?php
// app/controllers/IndexController.php

use Services/IndexService;

class IndexController extends BaseController
{
    public function index() { 
        return View::make('index', with(new IndexService())->indexData());
    }
}

可以使用更少的特定方法扩展此服务,您绝对应该更改命名(从IndexService和indexData到更具体的类/方法名称)。

如果您想了解有关使用服务的更多信息,我写了一篇很酷的文章here

希望这有帮助!