【问题标题】:Laravel eloquent hasOne select specific fields [duplicate]Laravel eloquent hasOne 选择特定字段 [重复]
【发布时间】:2021-04-05 17:09:45
【问题描述】:

假设我有 2 个表:

用户:

Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->integer('age')
$table->string('password');
$table->rememberToken();
$table->timestamps();
});

手机:

Schema::create('phones', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('phone');
$table->timestamps();

$table->foreign('user_id')->references('id')->on('users')
    ->onDelete('cascade');
});

用户模型:

public function phone()
{
    return $this->hasOne('App\Phone');
}

手机型号:

public function user()
{
    return $this->belongsTo('App\User');
}

当我执行以下查询时:

$result = User::select('name AS full_name', 'email AS user_email', DB::raw("'Student' as 
profile"))->where('age', '>', 10)->with('phone')->get();

我将手机设为 null

当只是表演时:

$result = User::where('age', '>', 10)->with('phone')->get();

我可以接电话。

【问题讨论】:

  • 你为什么使用DB::raw("'Student' as profile")

标签: mysql sql laravel eloquent


【解决方案1】:

您必须选择用户的id,否则Laravel无法将检索到的手机型号与相关的用户型号匹配。

$result = User::select(
    'id', // must include keys required for relationships
    'name AS full_name',
    'email AS user_email',
    DB::raw("'Student' as profile")
)
->where('age', '>', 10)
->with('phone')
->get();

【讨论】:

    猜你喜欢
    • 2017-12-27
    • 2014-11-29
    • 2016-03-17
    • 2020-06-02
    • 2017-02-22
    • 1970-01-01
    • 2016-11-05
    • 2019-03-04
    • 1970-01-01
    相关资源
    最近更新 更多