Reputation: 5608
I have two models Award
and GotAward
, GotAward
model have foreign key of Award
model.
What i want to fetch all records from Award
model and then check each Award
model id in GotAward
model, I have to show the user that "you have have these awards".
I have the following code :
$awards = App\Award::all();
foreach ($awards as $checkAward) {
$unlockedAwards = App\unlockedAward::where('award_id','=',$awards->id);
}
Is it a good practice ?
Upvotes: 0
Views: 93
Reputation: 1165
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class GotAward extends Model
{
public function award(){
return $this->hasOne('App\Award');
//You can also specify the relationship in case of different fields in the DB table. By convention Laravel will check award_id in gotawards table
/* return $this->hasOne('App\Award', 'award_id', 'gotaward_id');*/
}
}
After you query GotAward Model.
$result = $GotAward::where('condtion', 'value')->first();
$result->award->award_column_to_shwo_to_user
Will contain data from awards table.
Take a look at Eloquent relationship, here.
Upvotes: 1
Reputation: 2320
No please look into relationships
after specifying the hasMany in your Award Model you could do somthing like
$award->AllAwards()
Upvotes: 0