我试图得到以下回应:
"user": {
"id": 1,
"first_name": "john",
"last_name": "doe",
"email": "[email protected] /cdn-cgi/l/email-protection",
"phone_number": "12345678",
"email_verified_at": null,
"created_at": "2021-09-02T08:57:07.000000Z",
"updated_at": "2021-09-02T08:57:07.000000Z",
"country": {
"id": 1,
"name": "UK",
"phone_code": 44
}
}
代替:
"user": {
"id": 1,
"first_name": "john",
"last_name": "doe",
"email": "[email protected] /cdn-cgi/l/email-protection",
"phone_number": "12345678",
"email_verified_at": null,
"created_at": "2021-09-02T08:57:07.000000Z",
"updated_at": "2021-09-02T08:57:07.000000Z",
"country_id": 1
}
为了做到这一点,我在用户模型中使用了一个 mutator 函数:
public function getCountryIdAttribute(): Builder|null
{
return Country::where('id', $this->attributes['country_id'])
->get()
->first();
}
但是,国家/地区表已在外部数据库中找到,我已正确设置其连接。
但我按照这个创建了国家模型Laravel 文档 https://laravel.com/docs/8.x/eloquent:
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
/**
* The database connection that should be used by the model.
*
* @var string
*/
protected $connection = 'my second db connection name';
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'countries';
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'id';
/**
* The model's default values for attributes.
*
* @var array
*/
protected $attributes = [
'id',
'name',
'phone_code',
];
}
当我尝试获取用户时,出现以下错误:
{
"error": [
"App\\Models\\User::getCountryIdAttribute(): Return value must be of type ?
Illuminate\\Database\\Query\\Builder, App\\Models\\Country returned"
],
"message": "Unhandled server exception",
"code": 500
}
我试图尽可能多地解释我的情况。
感谢您的帮助。