mardi 12 novembre 2019

Using custom method names in Eloquents "One to many" relationship

I have 2 tables with simple one to many relation.

users table:

id (primary key)
-- other columns ...

posts table:

id (primary key)
user_id
-- other columns ...

In User model I have:

public function postsbla() {
    return $this->hasMany('App\Post');
}

In Post model I have:

public function usersbla() {
    return $this->belongsTo( "App\User" );
}

Then, one of my controller I have:

use App\User;
use App\Post;


public function index()
{
    $a = true;
    if($a) { // case 1
        $user_id = 1;
        $user_posts = User::find( $user_id )->postsbla;
        var_dump($user_posts); exit;
    }
    else { // case 2
        $post_id = 5;
        $post_owner_user_data = Post::find( $post_id )->usersbla;
        var_dump($post_owner_user_data); exit;
    }
}

if $a === true (case 1) then custom method name postsbla() works and var_dump returns valid object, but if $a === false, (case 2) then custom method name usersbla() not works and returns NULL.

P.S. if I use not usersbla name, but user instead, then case 2 works too and gives valid object.

Please tell me, why can I use custom method name for case 1, and can't use for case 2 ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire