0
votes

I want to show data from a database(sql) that is from a specific user.

I have 3 tables: Users Stores Areas

These are the following relationship between tables:

User hasOne Area Area hasMany Stores

Basically what I wanted to show is that every user has their own area that has many stores.

User model

function area() {
    return $this->hasOne('App\Area');        
}

Area model

 function user() {
    return $this->belongsTo('App\User');
}

function stores() {
    return $this->hasMany('App\Store');
}

Store Model

function area() {
    return $this->belongsTo('App\Area');
}

My database looks like this:

user table
id name role_id area_id

area table
id name user_id

store table
id name area_id

How can I access user->area->store?

This is what I got so far

function show() {
    $id= Auth::user()->id;
    $user = User::find($id);
    echo($user->area->stores);
}

Thank you

1
the user table shouldn't contain reference for table area i.e. the area_id column in the user table. the rest is good and should work what's the problem?SC0RP10N.MY7H
Are you doing blade or api design? and define "want to show"mrhn
Hi, Thanks for asking. You are right about not having the area_id in the user table. I have finally managed it to work by using the hasManythrough relationship. Thank you and god bless.Jeano

1 Answers

1
votes

you can use the hasManyThrough for get sotres of an area:

define stores function in User model

public function stores()
{
    return $this->hasManyThrough(Store::class, Area::class);
}

and use it :

$stores = auth()->user()->stores;

I hope be useful.