php - laravel eloquent for hasMany relation does not work -
i have these relations in database
schema::create('my_users', function (blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('fullname'); $table->string('username'); $table->string('password'); $table->string('photo'); $table->string('email'); }); and
schema::create('posts', function (blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('photo'); $table->text('caption'); $table->integer('like'); $table->integer('my_user_id'); }); my models :
class myuser extends model { public function post() { return $this->hasmany('app\post'); } } class post extends model { public function user() { return $this->belongsto('app\myuser'); } } now i'm trying user's data using following code :
$post = post::find(1); $user = $post->user; but doesn't work , $user null. i'm sure in posts table there record id 1. weird part no error when change method's name :
$post = post::find(1); $user = $post->somethingbullshit; i'm using laravel 5.3.
help please.
confirm naming class files starting upper case letters, , modify class declarations accordingly, such as:
class myuser extends model { public function post() { return $this->hasmany('app\post'); } } class post extends model { public function user() { return $this->belongsto('app\myuser'); } } you can select user when obtain post utilizing eloquent's with() method, , obtain $user variable $post variable, or use user property of post follows:
$post = post::with('user')->find(1); $user = $post->user;
Comments
Post a Comment