vendredi 15 avril 2022

Laravel conditional response from Model

I have three tables locations, unique_routes and tours, migration example is below.

// locations table
public function up() {
  Schema::create('locations', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name')->unique();
    // extra data ...
  });
}
    
// unique_routes table
public function up() {
  Schema::create('unique_routes', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('location_id_1')->unsigned();
    $table->integer('location_id_2')->unsigned();
    // extra data ...
  });
  Schema::table('unique_routes', function (Blueprint $table) {
    $table->foreign('location_id_1')->references('id')->on('locations')->onDelete('cascade');
    $table->foreign('location_id_2')->references('id')->on('locations')->onDelete('cascade');
  });
}

// tours table
public function up() {
    Schema::create( 'tours', function ( Blueprint $table ) {
        $table->increments( 'id' );
        // extra data ...
        $table->integer( 'unique_route_id' )->unsigned();
        $table->boolean( 'reverse_route' )->default( 0 );
        // extra data ...
    } );

    Schema::table( 'tours', function ( Blueprint $table ) {
        $table->foreign( 'unique_route_id' )->references( 'id' )->on( 'unique_routes' );
    } );
}

And Models:

class Tour extends Model {
    public function unique_route() {
        return $this->belongsTo( Route::class, 'route_id', 'id' );
    }
}

class UniqueRoute extends Model {
  public function location_one() {
    return $this->belongsTo('App\Location', 'location_id_1', 'id');
  }
  public function location_two() {
    return $this->belongsTo('App\Location', 'location_id_2', 'id');
  }
}

If I need location one name from unique route from tour:


$tour->route->location_one->name

It works OK.

The problem is that sometimes I need location_two object if "reverse_route" on tours is true! The question that I have is, how can I set conditional on Model? Or is there another approach?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire