[英]Can't get model relation in artisan custom command Laravel 5.4
I created an artisan custom command and in the handle() method i need to get a few info about users. 我创建了一个工匠自定义命令,并在handle()方法中需要获取一些有关用户的信息。
When i run: 当我跑步时:
handle() {
$users = User::all();
foreach($users as $user) {
$this->line($user->name);
}
}
it works, but i need something like: 它有效,但是我需要类似的东西:
handle() {
$users = User::all();
foreach($users as $user) {
$this->line($user->summoner->summoner_id);
}
}
And i get Trying to get property of non-object. 我得到试图获取非对象的属性。
If i run the same code above in a controller it works just fine. 如果我在控制器中运行以上相同的代码,则工作正常。
Does anyone have an idea? 有人有主意吗?
User model: 用户模型:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function summoner() {
return $this->hasOne('App\Summoner');
}
Summoner model: 召唤师模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Summoner extends Model
{
protected $table = 'summoners';
public $timestamps = true;
public function user() {
return $this->belongsTo('App\User');
}
}
As @aynber metnioned above, if DB field user
. 如上文@aynber所述,如果DB字段为user
。 summoner_id
can be set to NULL, then there are users without related Summoner
. summoner_id
可以设置为NULL,那么有些用户没有相关的Summoner
。
So you can use whereHas
method of the QueryBuilder, which will check relationship summoner
existence: 因此,您可以使用whereHas
方法,该方法将检查关系summoner
存在:
$users = User::whereHas('summoner')->get();
foreach($users as $user) {
$this->line($user->summoner->summoner_id);
}
Or you can check existens of the relationship summoner
for every selected user, but this approach may select redundant data from DB (if you need all users with non-NULL summoner_id
field): 或者,您可以检查每个选定用户的关系summoner
是否存在,但是这种方法可以从数据库中选择冗余数据(如果您需要所有具有非NULL summoner_id
字段的用户):
$users = User::all();
foreach($users as $user) {
if(empty($user->summoner)){
continue;
}
$this->line($user->summoner->summoner_id);
}
You can find more information about whereHas
method here: 您可以在此处找到有关whereHas
方法的更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.