从指向同一张表的两个关系中过滤名字和姓氏

问题描述 投票:0回答:3

我在first_name表中具有last_nameuser列,这些列又与order_iteminstructor_id都链接到user_id表的user表有关。

现在我正在OrderItem模型中定义关系,例如:

public function getInstructor() {
        return $this->hasOne(User::className(), ['id' => 'instructor_id']);
    }

public function getCustomerName() {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

并且在OrderSearch模型中

public $instructor;
public $name;

$query->joinWith(['instructor','location1','customerName n']);        

$query->andFilterWhere(['like', 'concat(user.first_name," ",user.last_name)',  $this->name]) 
        ->$query->andFilterWhere(['like', 'concat(user.first_name," ",user.last_name)',  $this->instructor]);

现在我出现类似错误

Method yii\db\ActiveQuery::__toString() must not throw an exception, 
caught Exception: Serialization of 'Closure' is not allowed

如果我要在joinwith中删除别名n,则会出现类似以下错误:语法错误或访问冲突:1066不是唯一的表/别名:'user'

The SQL being executed was: SELECT COUNT(*) FROM `order_item` LEFT JOIN `user` ON
`order_item`.`instructor_id` = `user`.`id` LEFT JOIN `location` ON `order_item`.`location_id` =  
`location`.`id` LEFT JOIN `user` ON `order_item`.`user_id` = `user`.`id`
php mysql yii2
3个回答
0
投票

这是一个有效的查询...,尽管我仍然不太了解它要实现的目标...

SELECT COUNT(*) 
  FROM order_item i
  LEFT 
  JOIN user u1
    ON u1.id = i.instructor_id 
  LEFT 
  JOIN location l
    ON l.id = i.location_id 
  LEFT 
  JOIN user u2
    ON u2.id = i.user_id 

0
投票

您可以尝试使其与此相似:

class Order {
...
  //first relation with table COMPANY
  public function getCustomer()
  {
      return $this->hasOne( Company::className(), ['id' => 'customerid'] ) //table COMPANY
                  ->andOnCondition( [ '==relationAlias==.type' => 'customer' ] );
  }

  //second relation with table COMPANY
  public function getSupplier()
  {
      return $this->hasOne( Company::className(), ['id' => 'supplierid'] ) //table COMPANY
                  ->andOnCondition( [ '==relationAlias==.type' => 'supplier' ] );
  }
...
}

然后我们可以写

$orders = Order::find()
                   ->alias( 'o' )
                   ->innerJoinWith('customer c')
                   ->innerJoinWith('supplier s');

建立查询

select o.* from order o
join company c on c.id = o.customerid and c.type = 'customer'
join company s on s.id = o.supplierid and s.type = 'supplier'

此问题在github上提出了解决方案:https://github.com/yiisoft/yii2/issues/10883


0
投票

当时我想的要简单得多,但是花了很多时间解决。但我仍不清楚为什么问题中的方法不起作用。

[就像我所做的一样,我按如下所示分隔查询并在查询中使用别名。

existing

$query->andFilterWhere(['like', 'concat(user.first_name," ",user.last_name)',  $this->name]) 
->$query->andFilterWhere(['like', 'concat(user.first_name," ",user.last_name)',  $this->instructor]);

更新

$query->andFilterWhere(['like', 'concat(n.first_name," ",n.last_name)',  $this->name]); 
$query->andFilterWhere(['like', 'concat(user.first_name," ",user.last_name)',  $this->instructor]);

并且运行正常。

© www.soinside.com 2019 - 2024. All rights reserved.