[英]laravel eloquent for hasMany relation does not work
我的數據庫中有這些關系
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');
});
和
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');
});
我的模特:
class myUser extends Model
{
public function post()
{
return $this->hasMany('App\post');
}
}
class post extends Model
{
public function user()
{
return $this->belongsTo('App\myUser');
}
}
現在我正在嘗試使用以下代碼獲取用戶數據:
$post = post::find(1);
$user = $post->user;
但它不起作用,並且$ user為NULL。 我確定在posts表中有一條ID為1的記錄。最奇怪的是,當我更改方法名稱時,我不會出錯:
$post = post::find(1);
$user = $post->somethingBullshit;
我正在使用laravel 5.3。
請幫助。
確認您要命名以大寫字母開頭的類文件,並相應地修改類聲明,例如:
class MyUser extends Model
{
public function post()
{
return $this->hasMany('App\Post');
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo('App\MyUser');
}
}
然后,您可以通過雄辯的 with()
方法來選擇獲取$user
,並從$post
變量中獲取$user
變量,或者僅使用post的user屬性,如下所示:
$post = Post::with('user')->find(1);
$user = $post->user;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.