简体   繁体   中英

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.

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 . summoner_id can be set to NULL, then there are users without related Summoner .

So you can use whereHas method of the QueryBuilder, which will check relationship summoner existence:

$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):

$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:


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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