Yii2 - left join on multiple condition

后端 未结 3 2063
醉话见心
醉话见心 2021-01-12 14:25

I have three tables with the following relations,

  ------- 1        0..* ------------
 |Product|-------------|Availability|
  -------               --------         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-12 14:43

    Use this:

    $sql = 'SELECT p.ID FROM product p 
    LEFT JOIN availability a ON a.productID=p.ID 
              AND a.start>=DATE_ADD(DATE(now()), INTERVAL 7 DAY)
    LEFT JOIN meta_data m ON m.ID=p.meta_dataID
    WHERE a.ID IS NULL
    AND m.published_state=1';
    
    $products = Product::findBySql($sql);
    

    Yii Active Record has a findBySql($sql) method that allows you to run and get the data from database using a raw SQL query. It helps a lot when you got confused with Yii's query method or when your query get more complicated to be ran with Yii as in your case I suppose.

    So basically, in above block of codes, you just put your raw SQL query to a variable called $sql, and use it as the parameter value of findBySql() method.

提交回复
热议问题