【问题标题】:laravel eloquent for hasMany relation does not worklaravel 雄辩的 hasMany 关系不起作用
【发布时间】:2017-07-28 15:55:12
【问题描述】:

我的数据库中有这些关系

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。 我确定在帖子表中有一条 id 为 1 的记录。 奇怪的是,当我像这样更改方法的名称时,我没有收到任何错误:

$post = post::find(1);        
$user =  $post->somethingBullshit;

我使用的是 laravel 5.3。

请帮忙。

【问题讨论】:

  • 我不确定,但我想我已经遇到了这个问题。我认为这是因为您的“帖子”课程的名称。尝试将模型和表重命名为“myPost”之类的名称,看看它是否有效。

标签: php laravel-5 eloquent relationship


【解决方案1】:

确认您以大写字母开头的类文件命名,并相应地修改您的类声明,例如:

class MyUser extends Model
{
    public function post()
    {
        return $this->hasMany('App\Post');
    }        
}

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo('App\MyUser');
    }
}

然后您可以在获取帖子时使用eloquent'swith() 方法选择用户,并从您的$post 变量中获取您的$user 变量,或者只需使用帖子的用户属性如下:

$post = Post::with('user')->find(1); 
$user = $post->user;

【讨论】:

  • 我也确定相关的用户记录存在。
  • 如果你返回 $post 它是否包含你期望的信息或者它也是空的/NULL?
  • No $post 符合预期数据。
  • @blank94 修改答案
  • 没有结果是一样的。这太简单的问题,但我不知道出了什么问题:(
猜你喜欢
  • 1970-01-01
  • 2023-04-07
  • 2019-08-13
  • 1970-01-01
  • 1970-01-01
  • 2016-09-28
  • 2020-08-27
  • 1970-01-01
相关资源
最近更新 更多