Error between account in 2 tables

Asked

Viewed 68 times

0

Sorry I wouldn’t experience in Latin, I’m starting the studies and need to consult a Mysql table according to the value of another table ex.:

Tabela Sessões 
|   id   |   nome   |
|   1    |   João   |
|   2    |   Fabio  |
|   3    |   Maria  |

Tabela Produtos
| id | sessao_id | nome       |
| 1  | 1         | Computador |
| 2  | 1         | Televisor  |
| 3  | 2         | Carro      |

Model Sessões

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\Produtos;
class Sessoes extends Model
{
protected $id = 'id';

public function produtos(){
    return $this->hasMany(Produtos::class);
}
}

Controller

namespace App\Http\Controllers\Site;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Categoria;
use App\Models\Sessoes;
use App\Models\Produtos;
class SiteController extends Controller
{
public function listaProdutos(){

    $idsessao = Sessoes::where('id', '2')->get()->first();

    $produtos = $idsessao->produtos;
    foreach ($produtos as $prod) {
        echo $prod->nome;
    }
}
}

Where I might be missing or failing to do something?

This returning me the following error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'produtos.sessoes_id' in 'Where clause' (SQL: select * from produtos Where produtos.sessoes_id = 2 and produtos.sessoes_id is not null)

Thank you very much.

  • If you don’t explain the mistake, we won’t know what you’re missing.

  • Edited with error return

1 answer

0


In its product table the foreign key was named sessao_id. However, Laravel is running SQL looking for sessoes_id. Note that in your bank the key is in SINGULAR and Laravel is looking in PLURAL.

Change your code to:

public function produtos(){
    return $this->hasMany(Produtos::class, 'sessao_id', 'id');
}

Source, customize foreign and primary key name.

  • Valew Vinicius Carra, that’s right! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.