php - Laravel 与多个模型的接口(interface)

标签 php interface laravel laravel-4 eloquent

我正在使用 Laravel 4.1 围绕现有数据库结构编写一个系统。当前系统基于两个网站,它们使用自己的表,ab,两者都是相同的。在我们重写另一个系统之前,这是一个不可避免的问题。

我需要能够使用 Eloquents 查询生成器同时查询两个表,因此我可能需要从两个表中获取行列表,或者 INSERTUPDATE 任何时候都可以。

目前我们有两个表的模型,但无法在它们之间链接并实现缺少的方法,例如 allfind

我们的想法是有一个接口(interface)将这些结果绑定(bind)在一起,但是我们根本不知道如何去做。

<?php

    interface HotelInterface {
        public function all();
        public function find();
    }

    use Illuminate\Database\Model;

    class Hotel implements HotelInterface {

    }

?>

这是我们迄今为止所拥有的一切。

最佳答案

我在 Laravel 论坛上提问并得到了我正在寻找的答案!我在这里重新发布以防万一。

我们实际上想要的是一个存储库,它看起来像这样:

<?php
    class HotelRepository {
        public $A;
        public $B;

        public function __construct(A $A, B $B) {
            $this->A = $A;
            $this->B  = $B;
        }

        public function find($iso = NULL, $hotelid = NULL) {
            $A = $B = NULL;

            if($iso !== NULL) {
                $A = $this->A->where('country', $iso);
                $B  = $this->B->where('country', $iso);

                if($hotelid !== NULL) {
                    $A = $A->where('id', $hotelid);
                    $B = $B->where('id', $hotelid);
                }
            }

            if($hotelid !== NULL) {
                if($A->first()) {
                    return $A->first();
                }
                if($B->first()) {
                    return $B->first();
                }
            }else{
                return $A->get()->merge($B->get());
            }
        }

        public function all() {
            $aCollection = $this->A->all();
            $bCollection  = $this->B->all();
            return $aCollection->merge($bCollection);
        }
    }

现在在我想调用它的 Controller 中,我只需添加:

<?php
    class HomeController extends BaseController {
        public function __construct(HotelRepository $hotels) {
            $this->hotels = $hotels;
        }
    }

现在我可以使用 $this->hotels 访问我创建的 findall 方法。

关于php - Laravel 与多个模型的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21681866/

相关文章:

php - 使用 php 从 json 文件中删除父 key

php - 注册不插入数据

php - 大型数据库的高性能 PHP 相似性检查

php - 使用 Doctrine 查询生成器获取所有订购的实体

objective-c - 不熟悉的@interface 声明

mysql - 计算mysql中列的行数

C++:C++ 类的共同祖先和接口(interface)/原型(prototype)是否相互排斥?

java - 强制执行静态方法所需的设计模式

php - 在 Laravel 中获取 Auth 用户 ID

php - cellmap中找不到Frame的解决方法