我有加入2表的问题,当我执行打击代码时结果代码正确,但是不要在结果中显示来自ticket_pin的pin字段
$model = Ticket::find()->leftJoin(TicketPin::tableName(), 'ticket.id=ticket_pin.ticket_id and ticket_pin.user_id=1')->all();
[id] => 1
[user_id] => 1
[receiver_user_id] =>
[title] => بسش
[problem] => شسبس
[text] => سشب
[receiver] => 1
[priority] => 1
[status] => 4
[seen] =>
[online] =>
[created_at] => 1490588016
但是当我使用createCommand时它会正确显示结果,但我需要使用ActiveRecord
Yii::$app->db->createCommand('SELECT * FROM ticket LEFT JOIN ticket_pin ON ticket.id=ticket_pin.ticket_id and ticket_pin.user_id=1 order by ticket.id DESC')->queryAll();
[id] =>
[user_id] =>
[reciver_user_id] => 1
[title] => سس
[problem] => afsfsa
[text] => sfaaf
[reciver] =>
[priority] => 1
[status] => 4
[seen] => 0
[online] =>
[{"user_id":2,"name":"\u0645\u062d\u0645\u062f","time":1491378729}]
[created_at] => 1491378692
[ticket_id] =>
[pin] =>
答案 0 :(得分:2)
通过以下查询,您将获得Ticket
模型属性。如果你想获得TicketPin
模型属性而不是在Ticket
模型中定义它们。
$model = Ticket::find()->leftJoin(TicketPin::tableName(), 'ticket.id=ticket_pin.ticket_id and ticket_pin.user_id=1')->all();
首先在Ticket模型类中定义属性,如下所示:
public $pin; // assuming you need pin attribute
现在在查询中添加select语句:
$model = Ticket::find()->select('ticket.*,ticket_pin.pin')->leftJoin(TicketPin::tableName(), 'ticket.id=ticket_pin.ticket_id and ticket_pin.user_id=1')->all();
现在你可以获得pin属性。
- >第二种方法是将查询输出作为数组,这样就不需要在模型中定义属性。
$model = Ticket::find()->select('ticket.*,ticket_pin.pin')->leftJoin(TicketPin::tableName(), 'ticket.id=ticket_pin.ticket_id and ticket_pin.user_id=1')->asArray()->all();
答案 1 :(得分:0)
您无法从TicketPin
AR模型本身获取Ticket
属性,但您可以从TicketPin
关系访问Ticket
(如果您已实施,或者Gii为此你)。
如果Ticket有很多 TicketPins,那么我认为,这种查询对您的情况是正确的:
$tickets = Ticket::find()->joinWith(['ticketPins' => function(ActiveQuery $query) {
$query->andWhere(['ticket_pin.user_id' => 1]);
}])->all();
foreach($tickets as $ticket) {
foreach($ticket->ticketPins as $ticketPin) {
echo $ticketPin->pin //Something like that
}
}
因此,在解释此代码时,您将获得具有Eager加载的TicketPins的Ticket模型(user_id=1
过滤包含在匿名函数中)。
对不起,如果给定的代码包含一些错误。我相信你可以重新检查它并使它对你的项目有用