使用Sql Data提供程序

时间:2015-06-26 05:02:12

标签: sql yii2

我想在SQL数据提供程序查询中使用条件,如下所示

 $count         =   Yii::$app->db->createCommand('
                    SELECT COUNT(*) FROM screen_ticket_booking WHERE id!=:id
                    ', [':id' => 0])->queryScalar(); 
                    $dataProvider = new SqlDataProvider([
                    'sql' =>    'SELECT A1.booking_id As Booking_id,
                                A3.movie_name As Movie,
                                A4.theatre_name As Theatre,
                                A1.show_date As Show_date,
                                A2.start_time As Time,
                                A5.booking_date As Booking_date,
                                A1.id As Id

                                FROM 
                                screen_ticket_booking A1

                                LEFT OUTER JOIN screen_show_times A2 ON A1.show_time_id=A2.id
                                LEFT OUTER JOIN movies A3 ON A1.movie_id=A3.id
                                LEFT OUTER JOIN theatres A4 ON A1.theatre_id=A4.id
                                LEFT OUTER JOIN screen_ticket_booking_history A5 ON A1.booking_id=A5.booking_id

                                WHERE A1.id !=0 ',
                    if( $userid != '1')
                    {
                    $sql .= ' AND A4.users_backend_id = {$userid}';
                    }   
                    'totalCount' => $count,
                    ]);

我收到错误“语法错误,意外'如果'(T_IF),期待']'” 。是不是可以在SQL数据提供程序中使用条件?

1 个答案:

答案 0 :(得分:3)

如果要使用条件来构建查询,则需要在 dataprovider 之外执行此操作。像这样:

$sql = 'SELECT A1.booking_id As Booking_id,
    A3.movie_name As Movie,
    A4.theatre_name As Theatre,
    A1.show_date As Show_date,
    A2.start_time As Time,
    A5.booking_date As Booking_date,
    A1.id As Id

    FROM 
    screen_ticket_booking A1

    LEFT OUTER JOIN screen_show_times A2 ON A1.show_time_id=A2.id
    LEFT OUTER JOIN movies A3 ON A1.movie_id=A3.id
    LEFT OUTER JOIN theatres A4 ON A1.theatre_id=A4.id
    LEFT OUTER JOIN screen_ticket_booking_history A5 ON A1.booking_id=A5.booking_id

    WHERE A1.id !=0 '

if( $userid != '1')
{
    $sql .= ' AND A4.users_backend_id = {$userid}';
}

然后$dataProvider = new SqlDataProvider([ 'sql' => $sql, 'totalCount' => $count, ]);

还考虑使用query builder,它提供了更灵活,更独立于DBMS的创建 SELECT SQL语句的方式