微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 一个模型中的多个表 – Laravel

我的索引页面数据库中使用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(不要重复自己)在某种意义上失去意义.

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

解决方法:

首先,我应该说每个模型都是针对特定的表编写的,除非它们是相关的,否则不能将三个表压缩到一个模型中. 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

希望这可以帮助!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐