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