Reputation: 337
I have the following database table structure
users table
id
mobile
name
devices
id
user_id
device
ip
active
one user can have multiple devices from which user will login
now the question is how to store and access the devices for particular user for example, user sam('id',1) has two devices android('user_id',1) and iphone('user_id',1). so when user will come and login i will have mobile no. to get the id of particular user from users table then i will run another query on devices table by user's id which i got from previous query and i have device ralated data.
but i know i am going wrong. what will be the other way .same happened when i am going to store user and related devices. first i store user and then by fetching id i store device for same user.
this is my User.php model
class User extends Model
{
protected $fillable = ['mobile','name'];
public function device(){
$this->hasMany('App\Device','tempuser_id');
}
}
Please tell me how can i deal with this by using eloquent one to many relationship.
Upvotes: 0
Views: 1394
Reputation: 544
To save devices for a particular user, you can use
public function add(Request $request){
$device= new \App\Device;
$device->user_id = $request->user()->id;
$device->device = $request->device;
$device->ip = $request->ip;
$device->active =$request->active;
$devices->save();
}
And to retrieve devices for a user, write in your controller
$devices = \App\User::find(Auth::user()->id)->devices;
Upvotes: 1
Reputation: 1835
In Model
public function devices()
{
return $this->hasMany('App\Device','user_id', 'id');
}
Add device to user
$user->devices()->save($device);
Get devices
foreach($user->devices as $device)
{
// device here
}
Upvotes: 1