Error between accounts in 2 tables laravel

0

Sorry for my not experiencing in laravel, I'm starting the studies and I need to consult a Mysql table according to the value of another table eg:

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 Sessions

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 can I go wrong or stop doing something?

This is returning me the following error

SQLSTATE [42S22]: Column not found: 1054 Unknown column 'products.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.

    
asked by anonymous 16.05.2018 / 19:52

1 answer

0

In your product table the foreign key was named session_id . However, Laravel is doing SQL execution looking for sessoes_id . Note that in your bank the key is in SINGULAR and Laravel is searching in PLURAL.

Change your code to:

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

Font , customize foreign and primary key name.

    
16.05.2018 / 22:21