How do I load a relationship from "belongsTo"?

Viewed 36

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

1 Answers

In your category model, have the following code:

public function tickets()
{
    return $this->hasMany(Ticket::class);
}

And add this in the ticket model:

public function category()
{
    return $this->belongsTo(Category::class);
}

Add in the PHP 8 stuff you have already, and it should work!

Edit: I saw you added more about how to load this properly. The code you already have in your controller should work with this as well. You'll maybe need to change the model class names in the methods I provided, but that should do the trick!

For more information about this type of relationship (one to many) read this part of the documentation.

Related