Skip to content
Advertisement

SQL join codeigniter 4

Codeigniter 4 is throwing the following error:

Argument 2 passed to view() must be of the type array, null given called in D:xampphtdocslordeCIappControllersBlog.php on line 35

That is about the block of code below:

public function post($post_id)
    {
        $model = new BlogModel();
        $posts = $model->select('*')->select('c1.nome as categoria, c2.nome as categoria_2')
            ->join('categorias c1', 'c1.categoria_id = posts.categoria', 'inner')
            ->join('categorias c2', 'c2.categoria_id = posts.categoria_2', 'inner')
            ->find($post_id);

        return view('posts/single_post',$posts);
    }

I am very grateful to who help me with that.

Advertisement

Answer

First you can remove the first select *, you either select * or define the fields you want.

You should do that only if you need all the columns from table 1 and just some from table 2.

Like so:

$model->select('*, c1.nome as categoria, c2.nome as categoria_2');

Second you need to send an array so that those keys can be turned into variables. In this case if you want a variable called posts in your view your should send it an index in your array.

    public function post($post_id)
    {
        $model = new BlogModel();
        $data['posts'] = $model->select('c1.nome as categoria, c2.nome as categoria_2')
             ->join('categorias c1', 'c1.categoria_id = posts.categoria', 'inner')
             ->join('categorias c2', 'c2.categoria_id = posts.categoria_2', 'inner')
             ->find($post_id);

        return view('posts/single_post',$data);
    }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement