由于多态关系,将表连接在两列中

时间:2018-06-01 10:45:23

标签: join laravel-5 eloquent polymorphism

我有以下结构:

Buro-> hasOne->地址 - > hasOne->都市> hasOne->状态 Buro-> hasOne->分类

命令中─> hasOne->地址 - > hasOne->都市> hasOne->状态 命令 - > hasOne->分类

类别 - > hasMany->订单和类别 - > hasMany-> Buros

我在一方的地址与另一方的Buro / Orders之间存在“一对多”的多态关系。只有一个buro的地址和一个订单的地址,因此我可以使用[0]来获得第一个也是集合中唯一的一个元素。

地址类

class Address extends Model
{
...

    public function addressable()
    {
        return $this->morphTo();
    }
...
}

Büro班级

class Buro extends Model
{
....
    public function addressable()
    {
        return $this->morphMany('App\Address', 'addressable');
    }
...
}

订购类

class order extends Model
{
....
    public function addressable()
    {
        return $this->morphMany('App\Address', 'addressable');
    }
...
}

现在我正在使用SELECT字段在前端构建一个表单,以便从Buros中选择只在订单所在的同一个州运行。

使用ELOQUENT我这样做了:

$all_bueros = Buero::where('category_id', $order->category_id)
                    ->where('title', $order->client->addressable[0]->city->state->title) // <- Look at this "title" column name
                    ->pluck('title', 'id')->all();

这里的问题是“标题”列名称不在“Buros”表中,而是在三个表之后。正好在: buros.addresses.city.state.title

我尝试过这些语法,但没有人工作:

->where('buros.addresses.city.state.title', $order->client->addressable[0]->city->state->title)   // as object notation

->where('buros->addressable[0]->cities->state->title', $order->client->addressable[0]->city->state->title)  // using the relation

我使用了查询构建器,但是更加混乱:

$buros = DB::table('buros')
                    ->join('categories', 'categories.id', '=', $order->category_id)
                    ->join('addresses', 'addresses.addressable_id', '=', $order->id, 'AND','addresses', 'addresses.addressable_type', '=', 'buros') //two points to join the table
                    ->join('cities', 'addresses.city_id', '=', 'cities.id')
                    ->join('states', 'cities.states', '=', 'states.id')
                    ->select('buros.title', 'buros.id')
                    ->where('states.title', '=', $order->client->addressable[0]->city->states->title)
                    ->get();

我的问题是如何将表连接成两点,因为存在多态关系。因为我需要加入“Buro-column”(addressable_type)和Buro-id列(addressable_id)中的地址表

任何帮助都会适用

0 个答案:

没有答案