princeoo7
3 months ago
876
15
Eloquent

hasMany relation gives perfect record, but belongsTo gives null.

Posted 3 months ago by princeoo7

I have 2 DB tables, One documents and other one is users.

code is as below for document where the issue is:

    public function user(){
            return $this->belongsTo(User::class, 'user_id')->orderBy('id', 'DESC');
        }

code for user, this gives results.:

    public function user(){
            return $this->hasMany(Document::class, 'user_id')->orderBy('id', 'DESC');
        }

I have already tried below code:

    public function user(){
            return $this->belongsTo(User::class, 'user_id', 'id')->orderBy('id', 'DESC');
        }

    //AND   
    
    public function user(){
            return $this->belongsTo(User::class)->orderBy('id', 'DESC');
        }

Well that's pretty much what issue have. I tried providing f_keys, still getting NULL on belongsTo relation. But on the other hand, if i try hasMany from other model, I do get the data.

//___ in controller


Request::whereId($id)->with(['documentsApi.docType', 'documentsApi.user')->first();

Please sign in or create an account to participate in this conversation.