0
votes

I am a newbie to Laravel 5.2 and am working on a legacy system and am a bit confused regarding eloquent and would appreciate someone giving me the code.

There are 3 tables:

cards categories cards2cat

cards can be part many categories which are kept in cards2cat table.

The cards2cat table has the following structure

id (primary key) image (card) category

What I want to do is to have a method in the Cards model called something like getCardsWithCategores which returned the cards info plus the names of the categories from the category table.

The categories table has a key of id and a field category.

Thanks!

1
Can you provide the migrations for the 3 tables?theMohammedA
As this is a legacy system I did not use migrations. The main points are cards is index on id, categories contains id and category, and card2cat is index on id with 2 other fields (both integer) image (which is the id of the card) and categoryAs this is a legacy system I did notJim

1 Answers

1
votes

Go to your Card2Cats model and add this:

public function categories()
{
    return $this->hasOne('App\Categories','id','category');

}

public function cards()
{
    return $this->hasOne('App\Cards','id','image');
}

For the query you do this:

$cards = Card2Cat::with('categories','cards')->get(); 
foreach ($cards as $key => $value) {
    echo $value->id.', Card:'.$value->cards->name.', Category:'.$value->categories->category.'<br>';

//$value->cards gives you all column of cards and you can do 
//$value->cards->colName
// same goes for $value->categories
}

Make sure the spelling of your classes and table column names are correct before running the code :D