简体   繁体   English

在工匠自定义命令Laravel 5.4中无法获得模型关系

[英]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方法的更多信息:


The only strange thing, that as you said (if I get you right), in non-artisan "regular" controller the same code executes without errors. 唯一奇怪的是,正如您所说的(如果我理解正确的话),在非熟练的“常规”控制器中,相同的代码可以正确执行。 Possible, it's just a coincidence: may be when you've checked your code in non-CLI (command line input) controller, all users had a summoner. 可能,这只是一个巧合:可能是当您在非CLI(命令行输入)控制器中检查了代码时,所有用户都有一个召唤者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM