如何将参数发送到Laravel?

时间:2019-05-09 07:15:12

标签: php laravel eloquent routes

我有医生和doctor_country_city表。

Schema::create('doctors', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('doctor_no')->unique();
        $table->string('slug')->unique();
        $table->string('fullname')->unique();
        $table->string('profile_image')->nullable();
        $table->date('birthday')->nullable();
        $table->enum('gender', ['male', 'female'])->nullable();
        $table->string('phone');
        $table->string('email');
        $table->string('password');
        $table->string('website_url')->nullable();
        $table->smallInteger('starting_month')->unsigned()->nullable();
        $table->year('starting_year')->nullable();
        $table->rememberToken();
        $table->timestamps();
        $table->dateTime('sort_date');
        $table->softDeletes();
    });


Schema::create('doctor_country_city', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('doctor_id');
        $table->unsignedInteger('country_id');
        $table->unsignedInteger('city_id');
        $table->timestamps();
        $table->foreign('doctor_id')->references('id')->on('doctors');
        $table->foreign('country_id')->references('country_id')->on('cities');
        $table->foreign('city_id')->references('id')->on('cities');
    });

我想向路由发送多个参数。我的控制器文件和模型关系应该是什么样的?

Example: Route::get('{country?}/{city?}/{slug?}', 'DoctorsController@showDoctor');

1 个答案:

答案 0 :(得分:1)

在为您提供解决方案之前,建议您重新考虑数据库设计。

医生可以属于许多城市吗?如果不是这样的话,您首先不需要doctor_country_city数据透视表。同样,您也不应将医生与城市和国家联系起来。这很奇怪,因为您的数据库可能允许指派一名医生到法国纽约。根据定义,一个城市仅属于一个国家。

因此,我宁愿将医生与与某个国家相关的城市联系起来。

Dr. John Doe > New York > USA

对我来说更有意义。因此,您将有一个名为countries的表,它们的模型将具有如下关系:

class Doctor extends Model {
   public function city() {
      return $this->belongsTo(City::class);
   }
}

class City extends Model {
   public function country() {
      return $this->belongsTo(Country::class);
   }
   public function doctors() {
      return $this->hasMany(Doctor::class);
   }
}

class Country extends Model {
   public function cities() {
      return $this->hasMany(City::class);
   }
}

一个国家可以有许多城市,但是一个城市属于一个国家。一个城市可以有很多医生,但是一个医生只能属于一个城市。

有关雄辩性关系check the documentation的更多信息。

关于您的问题,我想这是一个GET请求,您想从该城市获取所有医生。有很多方法可以实现这一目标。

您可以使用whereHas雄辩的方法来使用scope。这种方法可以根据相关表格中的值过滤您的Doctor模型结果。

我不想为您写下所有代码。我鼓励您阅读有关我上面列出的工具的文档。