在我的Web应用程序中,使用以下模型,我有两个表分别为users
和paymants
:
class User extends Authenticatable
{
use Notifiable;
protected $guarded = [
'id'
];
public function payments()
{
return $this->hasMany(Payment::class);
}
}
class Payments extends Model
{
protected $table = 'payments';
protected $guarded = ['id'];
public function users()
{
return $this->belongsTo(User::class);
}
}
每个用户都有很多付款记录,每个付款都属于一个用户,现在我通过查找用户来创建简单的付款记录
$user = User::find(2);
$user->payments()->create(
[
'resnumber' => 'dwwe',
'price' => '1111',
'invoice_id' =>'asdasd',
'month_key' => 'k8Cv2YfuO4jOLXd',
'month_id' => 6,
'payment' => false
]
);
此代码可以正常工作,并且可以创建成功的付款记录,现在我想例如通过关系船来获取此保存的记录:
$data = $user::with(['payments'])->first();
结果为空:
#relations: array:2 [▼
"payments" => Collection {#367 ▼
#items: []
}
完整的测试代码:
Route::get('/testPayment', function () {
$user = User::find(2);
$user->payments()->create(
[
'resnumber' => 'dwwe',
'price' => '1111',
'invoice_id' =>'asdasd',
'month_key' => 'k8Cv2YfuO4jOLXd',
'month_id' => 6,
'payment' => false
]
);
$data = $user::with(['payments'])->first();
dd($data);
});
迁移代码:
public function up()
{
Schema::create('payments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('month_id')->unsigned();
$table->foreign('month_id')->references('id')->on('months')->onDelete('cascade');
$table->string('month_key');
$table->string('resnumber');
$table->string('invoice_id');
$table->string('price');
$table->boolean('payment')->default(false);
$table->string('card_holder')->nullable();
$table->string('result_code')->default(0);
$table->timestamps();
});
}
现在有大问题
在将mysql数据库中的user_id值例如从2
更改为1
之后,我得到以下结果:|
#relations: array:2 [▼
"payments" => Collection {#378 ▼
#items: array:1 [▼
0 => Payment {#375 ▶}
]
此付款记录不适用于ID为2
的用户
答案 0 :(得分:0)
您正在创建一个新的User查询,该查询返回错误的User。
$user = User::find(2);
$user->payments()->create(
[
'resnumber' => 'dwwe',
'price' => '1111',
'invoice_id' =>'asdasd',
'month_key' => 'k8Cv2YfuO4jOLXd',
'month_id' => 6,
'payment' => false
]
);
$data = $user::with(['payments'])->first();
dd($data);
User
的{{1}} 2
创建付款User#2
个急于加载的User
,然后返回第一个之所以发生这种情况,是因为payments
既是$user
也是 User
模型。 User
不会说“为此用户付款”,而是说“获取所有$user::with
及其付款” –等效于User
您已经对User::with('payments')->first();
感兴趣,因此您的代码应如下所示:
User