0

I have two tables like below:

users table:

id - fname - lname

users_projects table:

id - user_id - title

my models are inside a directory called Models:

Users model :

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Users extends Model
{
    //

    public function usersProjects()
    {
        return $this->belongsTo(UsersProjects::class);
    }
}

UsersProjects model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UsersProjects extends Model
{
    protected $table = 'users_projects';
    //

    public function users()
    {
        return $this->hasOne(Users::class);
    }
}

now, I want to show last projects :

    $projects    = UsersProjects::limit(10)->offset(0)->get();

    var_dump($projects);
    return;

but my var_dump shows last projects ! I want to have fname and lname ! where is my wrong ?

1
  • each user can have some projects. now, I want to show projects . Commented Jul 22, 2016 at 18:10

2 Answers 2

1

I think you may have your relationships set up a little wrong. If a user can have more than one project, in your user model ...

public function usersProjects()
{
    return $this->hasMany(UsersProjects::class);
}

You might want to use a little simpler naming too ...

public function Projects()
{
    return $this->hasMany(UserProject::class);
}

(or simply Project if you don't have any other "Project" models)

The in your "Project" class ...

public function User()
{
    return $this->belongsTo(User::class);
}

(assuming you rename your model to User instead of "Users". Your table name should be "users" but a model is by nature a singular object. So it's appropriate to call it "User" - and your UsersProjects model should just be UserProject or just Project)

Now if you call the method something other than "User" you will have to add the foreign key name ...

public function SomeOtherName()
{
    return $this->belongsTo(User::class, 'user_id');
}

Then ...

$projects = Project::with('User')->limit(10)->offset(0)->get();

Will return a collection of projects with the User eager-loaded. (assuming you have renamed your UsersProjects model to "Project")

@foreach($projects as $project)
    ...
    First Name: {{ $project->User->fname }}
    ...
@endforeach
Sign up to request clarification or add additional context in comments.

Comments

0

Could you specify the relationships between the tables? (one to one, one to many) at first sight, I think that the relations are wrong

1 Comment

each user can have some projects. now, I want to show projects .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.