一个模型中的多个表 - Laravel

Pan*_*ply 3 php laravel eloquent laravel-4

我的索引页面在数据库中使用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()); 
}
Run Code Online (Sandbox Code Playgroud)

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

class IndexSlider extends Eloquent {
public $table ='index_slider';
}
Run Code Online (Sandbox Code Playgroud)

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

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

什么是最好的方法来到这里或我是在正确的轨道上?

小智 10

首先,我应该说每个模型都是针对特定的表编写的,除非它们是相关的,否则不能将三个表压缩到一个模型中.看这里

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

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

    return View::make('index', $data);
}
Run Code Online (Sandbox Code Playgroud)

将数据作为第二个参数传递.看这里

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

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

<?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;
    }
}
Run Code Online (Sandbox Code Playgroud)

和你的控制器:

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

use Services/IndexService;

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

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

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

希望这可以帮助!