Lazy load与参数的关系



我想用Laravel Eloquent Entity懒人加载产品

/**
* This is in my Orders model
*/
public function product($lang = '') {
switch ($lang){
case '':        return $this->belongsTo(ViewProducts::class, 'product_id', 'id');
case 'en_us':   return $this->belongsTo(ViewProductsEnUs::class, 'product_id', 'id');
}
}
/**
* This is what works. But its not lazy
*/
$orders = Oders::where('email','me@me.com')
->get();
foreach ($orders as $order){
$product = $order->products('en_us')->first();
}
/**
* This is what I want. Lazyload the product in a different language 'en_us'
*/
$orders = Oders::where('email','me@me.com')
->with('products', // I want to pass the param 'en_us' in any way //)
->get();

有谁知道如何传递参数(以任何方式)到雄辩实体,这样我就可以懒人加载我的产品数据?

我很感激你的帮助。

谢谢你@TimLewis!

而不是一个关系'product_'定义多个关系,如

/**
* In my Orders model
*/
public function product_() {
return $this->belongsTo(ViewProducts::class, 'product_id', 'id');
}
public function product_en_us(){
return $this->belongsTo(ViewProductsEnUs::class, 'product_id', 'id');
}

工作!

它不是完全完美的,因为你必须这样使用它:

$productRelation = 'product_' . $lang;
$orders = Oders::where('email','me@me.com')
->with($productRelation)
->get();
// And then get the data like this
$orders->{$productRelation};

但对我来说,这完全没问题!

最新更新