【发布时间】:2021-11-21 03:22:18
【问题描述】:
我有 3 张桌子
- 用户(ID、姓名、邮件、手机)
- 比赛(id,contest_name,contest_description)
- 竞赛用户 (id,user_id,contest_id)
我想在竞赛模型中编写一个有很多竞赛用户的方法,我还需要该方法中的用户详细信息。 请告诉我如何才能得到想要的结果。
<?php
namespace App\Model\Contest;
use App\Model\Project\ContestUsers;
use Illuminate\Database\Eloquent\Model;
class Contest extends Model
{
protected $table = 'contest';
protected $fillable = ['name','description'];
public $dates = [
'created_at',
'updated_at',
'deleted_at',
];
//I want to get user details from this method
public function project_contest_users()
{
return $this->hasMany(ContestUsers::class, 'contest_id', 'id')->whereNull('deleted_at');
}
}
【问题讨论】:
-
向我们展示您的代码 - 到目前为止您尝试过什么?
-
请用您尝试编写的代码编辑问题。
-
更新了问题。
-
请通过belongsToMany 关系。
-
您不需要
ContestUsers模型。这是一个 belongsToMany 关系的数据透视表。还要看看 Laravel 命名约定:它会让事情变得更容易:(你的命名空间应该是 UpperCamelCase,表名 'contests' 用于模型,'contest_user' 用于数据透视表......)
标签: laravel eloquent model relation