【发布时间】:2024-10-25 01:10:02
【问题描述】:
我需要根据父母的约束来获取一行的 ID。我想使用 eloquent 来做到这一点并保持优雅。此过程开始时需要注意的一些事项: 我有 - country_code(2 digit iso), lang_code(2 digit 语言缩写) 我需要 - country_id,lang_id(主键) 所以我可以得到 - market_id(最后一次查询需要)
我可以通过以下方式检索我需要的数据,抱歉变量的命名(客户端有奇怪的名称):
// Only receive desired inputs
$input_get = Input::only('marketCode','langCode');
// Need the country based on the "marketCode"
$countryId = Country::where('code',$input_get['marketCode'])->pluck('id');
// Get the lang_id from "langCode"
$languageId = Language::where('lang_abbr',$input_get['langCode'])->pluck('lang_id');
// Get the market_id from country_id and lang_id
$marketId = Market::where('country_id', $countryId)
->where('lang_id',$languageId)->pluck('market_id');
// Get All Market Translations for this market
$marketTranslation = MarketTranslation::where('market_id',$marketId)->lists('ml_val','ml_key');
我尝试了以下方法,但这只会根据限制急切加载国家/地区和语言。仅当 market_id 已知时,急切加载似乎才有帮助。
class Market extends Eloquent {
protected $primaryKey = 'market_id';
public function country() {
return $this->belongsTo('Country');
}
public function language(){
return $this->belongsTo('Language','lang_id');
}
}
$markets = Market::with(array(
'country' => function($query){
$query->where('code','EE');
},
'language'=> function($query){
$query->where('lang_abbr','et');
}
))->get();
【问题讨论】:
标签: php laravel eager-loading laravel-4 eloquent