简体   繁体   English

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

[英]Selecting data from different tables in laravel

I have a table of articles defined by their ID , name , price and category_ID and a table of categories defined by category_ID and name . 我有一个由其IDnamepricecategory_ID定义的文章表,以及由category_IDname定义的category_ID表。 I want to select into my controller, the list of articles, along with the category name . 我想选择我的控制器,文章列表以及类别name

How to do that? 怎么做?

My answer assumes you keep the models in App\\Models folder 我的回答是假设您将模型保存在App \\ Models文件夹中

In your Articles model define the following method. 在您的文章模型中定义以下方法。

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

You can access it now via $myArticle->category->name; 您现在可以通过$myArticle->category->name;访问它$myArticle->category->name;

Make sure in Categories model the correct table is defined, based on your question i can not make up the categorie table. 确保在Categories模型中定义了正确的表,根据您的问题,我无法组成类别表。

Put $table = 'categories'; $table = 'categories'; in the category model or whatever the table name is. 在类别模型中或表名称。

with raw SQL 用原始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)

or 要么

with Eloquent you can add a method to your model to return relationship , let's call it category 使用Eloquent你可以为你的模型添加一个返回关系的方法,让我们称之为category

class Article extends Model {
    public function category(){ 
        return $this->hasOne("App/Category" , "category_ID" , "category_ID");
    }
}

now you can do this 现在你可以做到这一点

$article = Article::find(1);
dump($article->category->name);

checkout hasOne method from the docs 从文档中checkout hasOne方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM