从laravel中的不同表中选择数据

问题描述 投票:0回答:2

我有一张由他们的IDnamepricecategory_ID定义的文章表,以及由category_IDname定义的类别表。我想选择我的控制器,文章列表,以及类别name

怎么做?

php laravel laravel-5 eloquent
2个回答
0
投票

我的回答是假设您将模型保存在App \ Models文件夹中

在您的文章模型中定义以下方法。

public function category()
{
    return $this->belongsTo('App\Models\Category');
}

您现在可以通过$myArticle->category->name;访问它

确保在Categories模型中定义了正确的表,根据您的问题,我无法组成类别表。

$table = 'categories';放在类别模型中或表名称中。


0
投票

与原始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方法

© www.soinside.com 2019 - 2024. All rights reserved.