簡體   English   中英

從 pivot 表中的 user_id 中獲取用戶名,並立即加載 laravel

[英]Get user name from user_id in pivot table with eager load laravel

我有 2 個模型和一個 pivot 表:

users
id

experiments
id

experiments_assigns
id
exp_id
user_id

pivot 表 experiments_assigns 有額外的字段,但我沒有為其創建特定的 model。 所以我想用他們的分配(如果有的話)和相關的用戶詳細信息來加載所有實驗。 除了獲取用戶詳細信息外,我可以讓它工作。在 controller 中,我有以下代碼:

$experiments = Experiments::with('assigns')->get();

但我無法弄清楚如何通過 pivot 屬性中返回的 user_id 加載關聯的用戶詳細信息。

這是實驗 class:

class Experminemts extends Model {
   
    public function assigns() {
        return $this->belongsToMany(
            Experminemts::class,
            'experminemts_assigns',
            'exp_id'
        )->withPivot('name', 'description', 'date_start',   'date_end', 'user_id');
    }
}

experiments_assigns 表遷移:

Schema::create('experiments_assigns', function (Blueprint $table) {
    $table->timestamps();
    $table->bigIncrements('id');
    $table->string('name');
    $table->text('description')->nullable(true); 
    $table->dateTime('date_start');
    $table->dateTime('date_end');
    $table->unsignedBigInteger('exp_id');//->unsigned()
    $table->unsignedBigInteger('user_id');
    $table->foreign('exp_id')->references('id')->on('experiments')
        ->onDelete('cascade');
    $table->foreign('user_id')->references('id')->on('users')
        ->onDelete('cascade');
});

所以我得到的分配是:

{ "exp_id": 6, "name": "實驗作業1", "description": null, "date_start": "2022-11-29 14:17:00", "date_end": "2022-12-30 14:17:00", "user_id": 9 }

我期望的地方:

{ "exp_id": 6, "name": "實驗作業1", "description": null, "date_start": "2022-11-29 14:17:00", "date_end": "2022-12-30 14:17:00", "user_id": 9, "user_name": "Some Name", "user_email": "some@ema.il" }

謝謝

您可以為 pivot 表 ExperimentAssign 創建 eloquent model 並在其中定義用戶關系:

public function user()
{
    return $this->belongsTo(User::class);
}

也許您還需要定義表格:

protected $table = 'experiments_assigns';

在你的實驗 model 添加關系:

public function experiment_assigns()
{
    return $this->hasMany(ExperimentAssign::class);
}

然后調用:

$experiments = Experiments::with('experiment_assigns.user')->get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM