在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');
}
}