Вопрос

I have two models (User and Services). What I want is to display all the services of a user. This is my action that show me all the services :

public function index()
{
    $services = Service::all();

    // load the view and pass the nerds
    return View::make('services.index')->with('services', $services);
}

and in my User model I add this function :

public function service()
{
    return $this->hasMany('Service');
}

Then in my service model :

public function user()
 {
     return $this->hasOne('User');
 }

So please if someone has any idea, I will be very appreciative :)

Это было полезно?

Решение

The relationships you are looking for for a 1-to-many relationship are hasMany() and belongsTo().

With that in mind, in your Service model, define the relationship like so...

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

It doesn't really matter too much in this scenario because you aren't using it, but it might save you some confusion later.

Now to get the users's services, you can use the User model.

$services = User::find(1)->services;

Or if you just want to get the logged in users's services...

$services = Auth::user()->services;

Другие советы

In your service model. Notice that you may have to define the local and foregin keys on these relationships

 public function user()
 {
   return $this->belognsTo('User');
 }

Then you can parse them in your controller or view (only the foreach part) like this

$user=User::find($id);
foreach($user->service as $service){
 //do something 
   echo $service->id
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top