无需经历这一切,然后如果您勤奋并想检查 getAttributes 或 toArray Laravel 函数返回什么以及发生了什么,我们可以使用 isset 和 is_null PHP 核心的组合职能。我在这里专注于 Laravel 和相应的关系,这是一个更复杂的示例,但所有其他变体都可以从下面的代码中提取。享受,我希望它会节省时间。
让我尝试用完整的 Laravel 示例和 Artisan Tinker 来详细说明。
请多多包涵。
谢谢PHP Artisan Tinker!
/**
* @return \Illuminate\Database\Eloquent\Model|HasMany|object|null
*/
public function profile(): HasMany
{
return $this->hasMany(User_profile::class, 'user_id', 'user_id')
->orderBy('created_at', 'desc');
}
php artisan tinker
>>> $u = (new App\Models\User())->find(11549)
=> App\Models\User {#3481
user_id: 11549,
created_at: "2019-10-31 09:26:14",
updated_at: "2019-10-31 09:26:14",
first_name: "Pippy",
middle_name: null,
last_name: "Longstocking",
phone: null,
email: "11544@example.com",
pincode: null,
flag_is_active: 0,
flag_is_email_subscribed: 1,
flag_is_mobile_subscribed: 1,
flag_terms_agreed: 1,
flag_is_blocked: 0,
flag_delete: 0,
where_from: 1,
employee_status: 0,
remember_token: null,
user_reference: "11544",
alternate_user_reference: "11544",
user_transaction_reference: null,
user_channel: null,
campaign_id: 0,
ip_address: "172.31.10.23",
}
>>> $u->profile()
=> Illuminate\Database\Eloquent\Relations\HasMany {#3483}
>>> $userProfile=$u->profile()->first();
=> null
>>> $userProfile->flag_ifisa
PHP Notice: Trying to get property 'flag_ifisa' of non-object in Psy Shell code on line 1
>>> $userProfile->toArray()
PHP Error: Call to a member function toArray() on null in Psy Shell code on line 1
>>> $userProfile->getAttributes()
PHP Error: Call to a member function getAttributes() on null in Psy Shell code on line 1
>>> is_null($userProfile)
=> true
>>> isset($userProfile->flag_ifisa)
=> false