简体   繁体   中英

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 . I want to select into my controller, the list of articles, along with the category name .

How to do that?

My answer assumes you keep the models in App\\Models folder

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;

Make sure in Categories model the correct table is defined, based on your question i can not make up the categorie table.

Put $table = 'categories'; in the category model or whatever the table name is.

with raw 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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