2019 年 10 月 4 日更新:
简而言之,NO,您可以使用Query Builder 而不是Eloquent ORM,但如果您想使用Eloquent ORM,那么每个表都必须绑定到model。此外,模型不一定必须是Eloquent model,您可以在不扩展可能使用或不使用数据库的 eloquent 模型的情况下创建模型。模型并不意味着数据库访问层,但是……无论如何,这是另一个大话题。
原答案:
如果你使用Eloquent,实际上你需要为你的两个表创建两个Eloquent模型,例如:
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');
}
}
现在创建OccasionCategory 模型:
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');
}
}
现在您可以使用类似这样的方式检索带有其父场合类别的场合:
// 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;
在Laravel 网站上阅读有关relationship 的更多信息。
如果你直接使用Query Builder,那么你可以使用这样的东西(没有模型):
// 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();
在Laravel 网站上阅读有关Query Builder 的更多信息。