Dosmukhanbet
1 month ago

Get nested subquery with eloguent

Posted 1 month ago by Dosmukhanbet

Hello, There are following relationships model Order belongsTo -> Point, Point belongsTo -> Country. I would like get in one query Orders with Point name, also Country name.

with below scope in Order model i get point name

public function scopeWithAPoint($query)
{
      $query->addSelect(['a_point_name' => Point::select('name')
                    ->whereColumn('id', 'orders.point_A_id')
                    ->limit(1)]);
  }

 Order::withAPoint() ->orderBy('created_at', 'desc')
                                    ->take(15)
                                    ->get();

but having trouble to get Country name, could somebody help me implement this

models 

class Order extends Model
{
   
    public function a_point()
    {
        return $this->belongsTo(Point::class, 'point_A_id');
    }

    public function scopeWithAPoint($query)
    {
      $query->addSelect(['a_point_name' => Point::select('name')
                    ->whereColumn('id', 'orders.point_A_id')
                    ->limit(1)]);
      }

}

class Point extends Model
{
    public function country()
    {
        return $this->belongsTo(Country::class);
    }
}

migrations:
Schema::create('points', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->unsignedBigInteger('country_id');
        });
    }

 Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('point_A_id');
            $table->timestamps();
        });

 Schema::create('countries', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('shortname');
            $table->string('language');
        });

Please sign in or create an account to participate in this conversation.