Home > Software engineering >  Laravel Eager loading ,relationship in builder be a value directly
Laravel Eager loading ,relationship in builder be a value directly

Time:09-17

it's a row with another row, condition on id to info_status

relationship

public function status(){

        return $this->hasOne(Row::class,'id','info_status')->select("id" ,"row")
    }

result

Row::with('status')->find(5588)

=> App\Models\Row {#3563
     id: 5588,
     info_status: "2637",
     status: App\Models\Row {#3576
       id: 2637,
       row: 1104,
     },
   }

how to get status->row->value ,become status->value at preloading sql builder ?

Is it possible ? doc didn't mention it.

//expect

=> App\Models\Row {#3563
     id: 5588,
     info_status: "2637",
     status: 1104,
     },
   }

CodePudding user response:

Assuming table name as rows, here is my solution:

$row = \Illuminate\Support\Facades\DB::table('rows')
    ->join('rows as related_rows', 'rows.info_status', 'related_rows.id')
    ->select('related_rows.row as status', 'rows.id', 'rows.info_status')
    ->get();

CodePudding user response:

You'll need to make use of an accessor.

The accessor retrieves the row value from the relationship and returns it as an attribute.

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class Row extends Model {

    public $appends = ['status'];

    //Relationship status
    public function statusRow(){
        return $this->hasOne(Row::class,'id','info_status');
    }

    /**
    *  Accessor to create status attribute and retrieve row value
    *  @return \Illuminate\Database\Eloquent\Casts\Attribute
    */
    */
    public function getStatusAttribute() : Attribute
    {
        return Attribute::make(
            get: fn () => $this?->statusRow->row;
        );
    }   
}

Source: https://laravel.com/docs/9.x/eloquent-mutators#defining-an-accessor

CodePudding user response:

Try this:

Row::with('status.row')->find(5588);
  • Related