So I have this model, 'Ticket' that contains (among other things) a "category_id" column.
To simplify, here is how my datas look:
Tickets table
| id | Title | category_id |
|---|---|---|
| 1 | Issue #1 | 2 |
| 2 | Issue #2 | 4 |
| 3 | Issue #3 | 1 |
Categories table
| id | Title |
|---|---|
| 1 | Authentication |
| 2 | Account |
| 3 | Billing |
In my Ticket model, I've done the following:
/**
* @return Category
*/
public function category(): Category
{
return Category::firstWhere($this->category_id);
// return $this->belongsTo('App\TicketCategory'); <-- how it was, can't eager load.
}
But I'm getting an undefined function addEagerConstraints().
Edit: here is my controller:
class TicketController extends Controller
{
public function index()
{
$tickets = Ticket::with('category')->all();
// dd($tickets);
return view('tickets.index', compact('tickets'));
}
}
I also tried with hasOne but this implies that "categories" needs a "ticket_id" column, which I want to avoid.
I'd like my models just to pick the category they are related to and nothing more.
What would be a solution here?
Thanks in advance