用hasMany relationship-laravel 4计算相关表的记录

时间:2014-08-07 07:53:25

标签: php mysql sql laravel orm

我有下表

cards
----------

id | name

card_pin
----------
id|card_id|pin

我需要将所有卡片及其引脚数量拉下来,如下所示

card        no_of_pins
c1            10
c2            20

我的模特

class Card extends \Eloquent {

    protected $table = 'cards';


     public function CardPin()    {
        return $this->hasMany('CardPin');
    }
}   

ORM

Card::where('is_active', '=', 'Y')->get();
inside the loop i have to do the following
Card::find(id)->CardPin()

有没有一种有效的方式来编写ORM,它很可能是

的复制品
SELECT 
card,
(SELECT count(pin) FROM card_pin cp where cp.card_id=cards.id) as no_of_pins
FROM
cards

0 个答案:

没有答案