限制急切的关系不起作用

时间:2014-04-09 10:58:15

标签: php pagination laravel-4 eager-loading

在tumblr上,泰勒说你可以像这样分享一个热切的关系:

$users = User::with('posts')->paginate();

但是这个不起作用

当我尝试它时,我添加了一个这样的foreach循环:

$products = Product::with('Fulfillment')->paginate(5);
foreach($products as $p){
    echo $p->id.' has '.$p->fulfillment->id."\n";
}

猜猜它运行了多少查询?那是对的。的

string(41) "select * from `products` limit 5 offset 0"
string(79) "select * from `fulfillment` where `fulfillment`.`product_id` in (?, ?, ?, ?, ?)"
string(72) "select * from `fulfillment` where `fulfillment`.`product_id` = ? limit 1"
string(72) "select * from `fulfillment` where `fulfillment`.`product_id` = ? limit 1"
string(72) "select * from `fulfillment` where `fulfillment`.`product_id` = ? limit 1"
string(72) "select * from `fulfillment` where `fulfillment`.`product_id` = ? limit 1"
string(72) "select * from `fulfillment` where `fulfillment`.`product_id` = ? limit 1"

起初我认为这可能是分页的问题,但后来我尝试了这个:

$products = Product::with('Fulfillment')->limit(5)->get();

和此:

$products = App::make('Product')->where('id', '=', '490920')->with('Fulfillment')->get();

我也遇到了同样的问题。它仍然为每个循环迭代重新加载履行类。到底是怎么回事?我必须对with做错事,但我怎么弄清楚是什么?

供参考,我的产品类:

class Product extends Eloquent {
    public function fulfillment() {
        return $this->hasOne('Fulfillment', 'product_id');
    }
}

0 个答案:

没有答案