在我的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);
}
}
每个用户都有许多付款记录,每个付款都属于一个用户,现在我使用finding 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();
结果为空:
#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数据库中更改用户id值后,例如
2
到
1
我有这个结果:|
#relations: array:2 [â¼
"payments" => Collection {#378 â¼
#items: array:1 [â¼
0 => Payment {#375 â¶}
]
此付款记录不适用于ID为的用户
二