use*_*894 15 php model laravel eloquent laravel-4
我正在用Laravel建立一个场合系统.我有几个表,如:
现在我有一个名为Occasion表示场表的模型,它还有一个对于occasion_categories表的外键.
我想检索所有场合类别,但是
我是否需要制作一个名为OccasionCategoryoccasion_categories 的分离模型并定义这些模型中的所有关系,
或者我可以只在Occasion类中创建一个方法getCategories()然后使用DB类DB::table('occasion_categories')->get()来检索所有可能的类别?
The*_*pha 10
实际上NO,如果您正在使用Query Builder,则需要为两个表创建两个模型,例如:
class Occasion extend Eloquent {
// Laravel will look for occasions table for Occasion model so following line
// is optional if you don't want to use another table name for Occation model
protected $table = 'occasions';
// Now declare the relationship with "occasion_categories" table
public function occasionCategory()
{
// Make sure you have used occasion_categories_id as the foreugn key
return $this->belongsTo('OccasionCategory', 'occasion_categories_id', 'id');
}
}
Run Code Online (Sandbox Code Playgroud)
现在创建Eloquent ORM模型:
class OccasionCategory extend Eloquent {
protected $table = 'occasion_categories';
// Now declare the relationship with "occasion_categories" table
public function occasions()
{
// Make sure you have used occasion_categories_id as the foreign key
return $this->hasMany('Occasion', 'occasion_categories_id', 'id');
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用以下内容检索具有父级occasion_category的场合:
// Use the Occasion model
$allOccasionsWithCategory = Occasion::with('occasionCategory')->get();
// Find one Occasion whose id is 1 with OccasionCategory
$oneOccasionsWithCategory = Occasion::with('occasionCategory')->find(1);
// You may use this to get the related occasionCategory model
$occasionCategory = $oneOccasionsWithCategory->occasionCategory;
// Use the OccasionCategory model
$allOccasionsWithCategory = OccasionCategory::with('occasions')->get();
// Find one OccasionCategory whose id is 1 with Occasion
$oneOccasionsWithCategory = OccasionCategory::with('occasions')->find(1);
// You may use this to get all the related occasions model
$occasions = $oneOccasionsWithCategory->occasions;
Run Code Online (Sandbox Code Playgroud)
阅读更多关于网站关系的Eloquent ORM信息.
如果你model直接使用那么你可以使用这样的东西(没有模型):
// All occations
$occations = DB::table('occations')->get();
// All occasions and related occasion_categories
$occationsAndCategories = DB::table('occations')
->join('occasion_categories', 'occasions.occasion_category_id', '=', 'occasion_categories.id')
->get();
Run Code Online (Sandbox Code Playgroud)
在网站上阅读有关Query Builder的更多信息Eloquent model.
该laravelish方式做数据库使用的是查询生成器或机锋:Laravel是一个框架,它总是有道理利用它暴露的资源.
简短的回答:
- 不,只要你不使用Eloquent就没有 .
答案很长:
该查询生成器是去,如果你仍然要坚持laravel约定的方式.
您也可以使用普通的旧PDO:记住Laravel实际上是一个PHP框架!
保持一致总是有益的:
这样做Eloquent(模型+关系定义),尽管你可以混合Eloquent和Query Builder你建议的一些.
Query Builder专门使用它也是一致且可能的.
我个人倾向于Eloquent选择.
WereWolf - Alpha 答案使用这两个选项提供了出色的解决方案.
虽然我并不乐观,但我很确定这会起作用。或者,DB::raw('select * from occasion_categories')应该有效。
我不知道这里的最佳实践是什么,但如果您只是问是否可能,那么是的。这两种方法之一应该可以正常工作。
| 归档时间: |
|
| 查看次数: |
8338 次 |
| 最近记录: |