我是Laravel的初学者,我正在尝试documentation中所述的firstOrNew
雄辩的方法。
我在MySQL中有下表:
SELECT * FROM `ratings`;
+----+-----------+-----------+--------+---------------------+---------------------+
| id | realty_id | client_id | rating | created_at | updated_at |
+----+-----------+-----------+--------+---------------------+---------------------+
| 1 | 67 | 29548 | -1 | 2019-03-23 12:14:32 | 2019-03-23 12:26:57 |
| 2 | 67 | 29549 | 1 | 2019-03-23 12:14:53 | 2019-03-23 12:14:53 |
| 3 | 67 | 29547 | 1 | 2019-03-23 12:20:47 | 2019-03-23 12:20:47 |
| 4 | 67 | 29546 | 1 | 2019-03-23 12:24:47 | 2019-03-23 12:26:52 |
+----+-----------+-----------+--------+---------------------+---------------------+
4 rows in set (0,00 sec)
在Laravel中,我的Rating
模型设置如下:
<?php
namespace App\Models;
use App\Models\BaseModel;
class Rating extends BaseModel
{
protected $table = 'ratings';
protected $fillable = [
'client_id',
'realty_id',
'rating',
];
public function realty()
{
return $this->belongsTo('App\Models\Realty');
}
public function client()
{
return $this->belongsTo('App\Models\Client');
}
}
当我尝试通过传递现有的client_id
和realty_id
来检索现有的记录时,我得到了预期的结果:
$rating = Rating::firstOrNew([
'client_id' => 29548,
'realty_id' => 67,
]);
dd([$rating->client_id, $rating->realty_id]);
/*
Results in
array:2 [▼
0 => 29548
1 => 67
]
*/
但是,当我在不存在的client_id
上尝试相同的代码时(例如这是他第一次提交评级),两个属性都得到null
:
$rating = Rating::firstOrNew([
'client_id' => 29550, // THIS ID IS NOT IN THE `ratings` TABLE
'realty_id' => 67,
]);
dd([$rating->client_id, $rating->realty_id]);
/*
Results in
array:2 [▼
0 => null
1 => null
]
*/
如果我尝试使用firstOrCreate
而不是firstOrNew
,则会收到内部服务器错误,并显示以下消息:
SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:外键约束失败(
aptoadmi_aptovc
。ratings
,CONSTRAINTrealty_ratings_fk
外键({{ 1}})参考(realty_id
(realties
)在更新级联上删除级联(SQL:插入到id
(ratings
,updated_at
)值中(2019 -04-09 17:44:09,2019-04-09 17:44:09))
这是可以预期的,因为created_at
和client_id
的值不会传递到realty_id
语句。
我在做什么错了?