我正在使用 Laravel 4.1 围绕现有数据库结构编写一个系统。当前系统基于两个网站,它们使用自己的表,a
和 b
,两者都是相同的。在我们重写另一个系统之前,这是一个不可避免的问题。
我需要能够使用 Eloquents 查询生成器同时查询两个表,因此我可能需要从两个表中获取行列表,或者 INSERT
或 UPDATE
任何时候都可以。
目前我们有两个表的模型,但无法在它们之间链接并实现缺少的方法,例如 all
或 find
。
我们的想法是有一个接口(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
访问我创建的 find
和 all
方法。
关于php - Laravel 与多个模型的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21681866/