How can I solve issue with One to One relationship using foreign keys
سؤال
I've been using eloquent in my models. I've got the following two tables:
Singlecard
->id
->card_id
Card
->id
->card_id
My Singlecard Model has the following function:
public function info()
{
return $this->hasOne('Card', 'card_id', 'card_id');
}
I used this to get the card (there's only one card in the deck for my test).
$cards = Singlecard::where('deck_id', '=', $deck)->get();
foreach ($cards as $card)
{
$cards_array[] = $card;
}
It got the correct card and using var_dump I verified that. However, here's the problem:
<div class="row singlecard">
<a class="" href="{{ $single->id }}">
<div class="large-2 columns">
<img src="{{ $single->info->card_image }}">
</div>
<div class="large-10 columns">
<div class="row">
<div class="large-12 columns">
<p>{{ $single->info->name }}</p>
</div>
</div>
<div class="row">
<div class="large-12 columns">
@foreach ($single->attributes as $attribute)
<p>{{ $attribute->alias }}</p>
@endforeach
</div>
</div>
</div>
</a>
</div>
Here's the twist: The attributes code works correct. It grabbed the correct attributes from a one to many relationship I defined. But it's grabbing the wrong info from the Cards table. Even though I defined the keys to match on, it is matching based on the ID of the singlecard and the card_id in the Cards table.
I've tried removing the keys and that didn't do anything. I even removed the function all together just to verify that that was the function being called. I'm not sure what's wrong?
UPDATE:
I figured it out, I did two things. One, I used id from the Cards table as the record to match with Singlecards. I also changed my function in the Singlecards model like so:
public function info()
{
return $this->belongsTo('Card', 'card_id');
}
This allowed me to properly query the relationship.
المحلول
I needed to update how my models were related and better form the relationship. I also needed to change the model so that Singlecards belonged to Cards. I assumed it should be the opposite.
Cards contains all the info about the various cards and Singlecards is what is in each individuals hands/decks. I assumed that would make Singlecards the parent but that was a mistake. Once I changed the function in the model to be like this:
public function info()
{
return $this->belongsTo('Card', 'card_id');
}
Then it worked.