[英]how to use a simple Relationships in laravel
I have two tables like below: 我有两个如下表:
users
table: users
表:
id - fname - lname
users_projects
table: users_projects
表:
id - user_id - title
my models are inside a directory called Models
: 我的模型位于名为
Models
的目录中:
Users
model : Users
模型:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
//
public function usersProjects()
{
return $this->belongsTo(UsersProjects::class);
}
}
UsersProjects
model: UsersProjects
模型:
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 ! 但是我的
var_dump
显示了最近的项目! I want to have fname
and lname
! 我要有
fname
和lname
! where is my wrong ? 我哪里错了?
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) (假设您将模型重命名为User而不是“ Users”。表名应为“ users”,但模型本质上是单个对象。因此,将其称为“ User”是适当的-而UsersProjects模型应该只是UserProject或只是项目)
Now if you call the method something other than "User" you will have to add the foreign key name ... 现在,如果调用该方法而不是“ User”,则必须添加外键名称...
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")
(假设您已将UsersProjects模型重命名为“ Project”)
@foreach($projects as $project)
...
First Name: {{ $project->User->fname }}
...
@endforeach
Could you specify the relationships between the tables? 您可以指定表之间的关系吗? (one to one, one to many) at first sight, I think that the relations are wrong
(一对一,一对多)一见钟情,我认为这种关系是错误的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.