【问题标题】:Laravel, Call to a member function sync() on nullLaravel,在 null 上调用成员函数 sync()
【发布时间】:2018-02-11 10:05:14
【问题描述】:

我的 laravel 项目中有一个 FatalThrowableError - 在 null 上调用成员函数 sync()。调试器显示mi,就是这行代码

Post::findOrFail($post_id)->tags()->sync([1, 2, 3], false);

这一行的完整方法如下所示:

public function store(Request $request)
{
      // validate a post data
    $this->validate($request, [
            'title' => 'required|min:3|max:240',
            'body' => 'required|min:50',
            'category' => 'required|integer',
        ]);

    // store post in the database
    $post_id = Post::Create([
        'title' => $request->title,
        'body' => $request->body,
    ])->id;

    Post::findOrFail($post_id)->tags()->sync([1, 2, 3], false);

    // rediect to posts.show pages
    return Redirect::route('posts.show', $post_id);
}

我的帖子模型看起来像

class Post extends Model
{
    protected $fillable = [ ... ];

    public function category() {...}

    public function tags()
    {
       $this->belongsToMany('App\Tag', 'post_tag', 'post_id', 'tag_id');
    }
}

我的 Tag 模型看起来像

class Tag extends Model
{
    protected $fillable = [ ... ];

    public function posts()
    {
        return $this->belongsToMany('App\Post', 'post_tag', 'tag_id', 'post_id');
    }
}

感谢您的分析!

【问题讨论】:

  • 您的tags() 方法缺少return 语句:return $this->belongsToMany('App\Tag', 'post_tag', 'post_id', 'tag_id');

标签: laravel eloquent fatal-error laravel-eloquent


【解决方案1】:

试试这个

// store post in the database
$post = new Post([
    'title' => $request->title,
    'body' => $request->body,
]);

$post->save();

$post->tags()->sync([1, 2, 3], false);

【讨论】:

  • 感谢您的分析器,但这并不能解决我的问题。我有同样的错误。累了之后:
    $post = new Post; <br/> $post->title = $request->title;<br/> $post->body = $request->body;<br/> $post->save();<br/> $post->tags()->sync([1, 2, 3], false);
  • 你能在帖子表中插入新帖子吗?为什么你使用 [1,2,3] 而不是 $request->tags..
  • 是的,我在这个表中创建一个新帖子是正确的。我使用 [1, 2, 3] 因为这只是测试数组,在致命错误之后
  • 通过删除同步方法中的 false 重试
  • 我在问这个问题之前尝试了这个,很遗憾这没有用
【解决方案2】:

错误表明您在空对象上调用sync(),这意味着您的tags() 方法的结果是null

如果您查看tags() 方法,您会发现您忘记了return 关系,因此它返回null。添加return 关键字,你应该会很好。

public function tags()
{
    return $this->belongsToMany('App\Tag', 'post_tag', 'post_id', 'tag_id');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-04
    • 2016-06-29
    • 2018-04-03
    • 2021-10-06
    • 2019-06-17
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多