Do you have a country_id in your users table? It doesn't look like it, and I think you need one in order for the public function country() to work in your User Model.
How can i fetch a data from 3 tables with relationship
i wanted to fetch a data from 3 tables with relationship but it is not working for me and i needed help.
my tables are
- Users table
Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); });
-
Countries table
Schema::create('countries', function (Blueprint $table) { $table->increments('id'); $table->string('name_en'); $table->string('name_fr'); $table->string('short_code'); $table->string('id_region'); $table->timestamps(); $table->softDeletes(); }); -
food_and_feeds table
Schema::create('food_and_feeds', function (Blueprint $table) { $table->increments('id'); $table->string('Sample_code'); $table->string('Latitude'); $table->string('Longitude'); $table->unsignedInteger('users_id')->nullable(); $table->foreign('users_id')->references('id')->on('users'); $table->timestamps(); $table->softDeletes(); });
My models
- User Model
public function country() {
return $this->belongsTo('App\Country');
}
public function food_and_feed()
{
return $this->hasMany('App\food_and_feed','id');
}
- Country Model
public function users(){
return $this->hasMany('App\User','country_id');
}
- Food and feed model
public function users(){
return $this->belongsTo('App\User','users_id','id');
}
i can fetch the user_id from my food and fed relation ship but i wanted to fetch the user country through its id from the relationship in food and feeds view.
i can fetch the users name using this
<td> {{$food->users->name}} </td>
but i want to fetch the users country name
how can i do this? thanks in advance.
Please or to participate in this conversation.