无法获得多对多关系,但附加/分离在Laravel 5.2中正常工作

时间:2016-11-16 03:39:20

标签: php database laravel laravel-5 eloquent

完整错误是:

1066 Not unique table/alias: 
SQL: select `salons_services_salons_services_sex`.*,
    `salons_services_salons_services_sex`.`salons_services_id` as `pivot_salons_services_id`,
    `salons_services_salons_services_sex`.`salons_services_sex_id` as `pivot_salons_services_sex_id`
from `salons_services_salons_services_sex`
    inner join `salons_services_salons_services_sex` on `salons_services_salons_services_sex`.`id` = `salons_services_salons_services_sex`.`salons_services_sex_id`
where `salons_services_salons_services_sex`.`salons_services_id` = 92

型号:

class SalonService extends Model
{

    public function sex() {
        return $this->belongsToMany('App\Models\SalonServiceSex',
            'salons_services_salons_services_sex',
            'salons_services_id',
            'salons_services_sex_id')
        ;
    }
}

尝试使用$ service->获取相关记录会导致错误,但attach()或detach()正常工作,因此我可以使用此方法链接模型。

修改 将生成的查询更新为

select `salons_services_salons_services_sex`.*,
  `salons_services_salons_services_sex`.`salons_services_id` as `pivot_salons_services_id`,
  `salons_services_salons_services_sex`.`salons_services_sex_id` as `pivot_salons_services_sex_id`
  from `salons_services_salons_services_sex`
    inner join `salons_services_sex` as s1
      on s1.`id` = `salons_services_salons_services_sex`.`salons_services_sex_id`
  where `salons_services_salons_services_sex`.`salons_services_id` = 93

并且工作正常

获取相关记录:

$service->sex;

表:

salons_services:
id
name
time

salons_services_salons_services_sex:
salons_services_id
salons_services_sex_id

salons_services_sex:
id
name

0 个答案:

没有答案