【问题标题】:Laravel model relationship methodLaravel 模型关系方法
【发布时间】:2021-11-21 03:22:18
【问题描述】:

我有 3 张桌子

  1. 用户(ID、姓名、邮件、手机)
  2. 比赛(id,contest_name,contest_description)
  3. 竞赛用户 (id,user_id,contest_id)

我想在竞赛模型中编写一个有很多竞赛用户的方法,我还需要该方法中的用户详细信息。 请告诉我如何才能得到想要的结果。

Model Screenshot

<?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


【解决方案1】:

contest_useruserscontests 的数据透视表,不应有模型类。

User和Contest之间的关系本质是多对多的,所以两边都需要使用belongsToMany()关系

竞赛.php

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

用户.php

public function contests()
{
    return $this->belongsToMany(Contest::class);
}

【讨论】:

    【解决方案2】:

    根据我的经验,从您所做的事情来看,将多对多关系正常化已经是一件好事。但是 N69S 说的也是正确的,数据透视表不应该有 Model 类,所以你需要制定自己的约定,不使用 Model 类来创建/更新/删除(我可以阅读),如果你仍然想要要坚持这种方法,您现在需要做的只是定义每个模型的关系。

    用户.php:

    public function contest_user()
    {
        return $this->hasMany(ContestUser::class);
    }
    

    竞赛用户.php:

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

    竞赛.php:

    public function contest_user()
    {
        return $this->hasMany(ContestUser::class);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-23
      • 2018-01-08
      • 2019-04-04
      • 2021-11-06
      • 2020-04-02
      • 2018-07-11
      • 2016-11-01
      相关资源
      最近更新 更多