Add Pivot table for the relationship between Cities and Companies.
This commit is contained in:
@@ -4,6 +4,7 @@ namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
class City extends Model
|
||||
{
|
||||
@@ -15,6 +16,11 @@ class City extends Model
|
||||
'url',
|
||||
];
|
||||
|
||||
public function companies(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Company::class, 'cities_companies', 'city_id', 'company_id');
|
||||
}
|
||||
|
||||
public static function validate_with_name(string $name)
|
||||
{
|
||||
$name = $name ?? '';
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Models;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
class Company extends Model
|
||||
{
|
||||
@@ -17,6 +18,11 @@ class Company extends Model
|
||||
'description',
|
||||
];
|
||||
|
||||
public function cities(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(City::class, 'cities_companies', 'company_id', 'city_id');
|
||||
}
|
||||
|
||||
public function categories(): HasMany
|
||||
{
|
||||
return $this->hasMany(Category::class);
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('cities_companies', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->unsignedBiginteger('city_id')->unsigned();
|
||||
$table->unsignedBiginteger('company_id')->unsigned();
|
||||
|
||||
$table->foreign('city_id')->references('id')
|
||||
->on('cities')->onDelete('cascade');
|
||||
$table->foreign('company_id')->references('id')
|
||||
->on('companies')->onDelete('cascade');
|
||||
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('cities_companies');
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user