Laravel belongsTo return null

2019-09-19 08:25发布

问题:

i have two model

Word Model:

class Word extends Model
{
 public function pos()
    {
        return $this->belongsTo(Pos::class);
    }
}

and PoS Model:

class Pos extends Model
{
    //
    protected $table = 'pos';
    public $timestamps = false;
}

now in controller i want to get word and pos relationship but pos relationship return null when i specify the columns

Controller

$word = Word::with(['pos'])->whereId( $vocabulary->word_id)->get(['id', 'word', 'surface', 'gloss', 'example','sound_url'])->first();

note when i use query without specify the columns work perfectly

   $word = Word::with(['pos'])->whereId( $vocabulary->word_id)->first();

i have been tried use addselect , with closure but same result

回答1:

Maybe try to add pos_id to that columns array.