我有一张由他们的ID
,name
,price
和category_ID
定义的文章表,以及由category_ID
和name
定义的类别表。我想选择我的控制器,文章列表,以及类别name
。
怎么做?
我的回答是假设您将模型保存在App \ Models文件夹中
在您的文章模型中定义以下方法。
public function category()
{
return $this->belongsTo('App\Models\Category');
}
您现在可以通过$myArticle->category->name;
访问它
确保在Categories模型中定义了正确的表,根据您的问题,我无法组成类别表。
将$table = 'categories';
放在类别模型中或表名称中。
与原始SQL
$query = "SELECT articles.* , categories.name AS categoryName FROM articles JOIN categories ON articles.category_ID = categories. category_ID"
$result = \DB::select(SQL);
dump($result)
要么
使用Eloquent
你可以为你的模型添加一个返回关系的方法,我们称之为category
class Article extends Model {
public function category(){
return $this->hasOne("App/Category" , "category_ID" , "category_ID");
}
}
现在你可以做到这一点
$article = Article::find(1);
dump($article->category->name);
从文档中检出hasOne
方法