Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chmureck's avatar

Querying foreign table in model.

Hi,

Two sql tables: products and colors Each color has id and name. Each product has top_color, side_color, bottom_color. All 3 are foreign keys with id from color table.

I want to write a product model in such a way that all queries will get me a name of the color, not it's id.

I can do it with accessor or mutator but there's got to be some nicer cleaner solution for this in Eloquent. After all, it's a very common problem.

Any suggestions appreciated.

0 likes
5 replies
jasonlimantoro's avatar

I'm not sure why you use accessors or mutators instead of an Eloquent relationships.

Can you so something like

Product.php

public function top()
{

    return $this->belongsTo(Color::class, 'top_color', 'id', 'top');
}

for all methods top(), side(), bottom().

In that way, given a $product, you can get the color's name of its top by doing

$topColor = $product->top->name;

and similarly for side's color and bottom's color as well.

Hope this helps.

chmureck's avatar

Ok, perhaps I wasn't clear in my description of the problem. I know how relationships work and I'm using them.

What I wanted to accomplish is to have a model replace the top_color, side_color and bottom_color with their names from the colors table.

I can do this by setting up the relationship and then using the accessor to replace the values but I was hoping that perhaps there is some builtin solution.

Mithrandir's avatar

setting up the relationship and using accessors is a builtin solution.

I wonder about the why, though - what are you trying to accomplish (in broader terms - like "I want to return a JSON object directly from the attributes" rather than "I want to build a query that returns this")

I guess you could do a Product::select() where you join the colors table once for each color attribute and use SQL aliases to get the color name into the attribute name - but there is still the "why" as to why that is a better solution than an accessor.

chmureck's avatar

Thanks for the reply.

Sure, I can use select but the goal was to have it all done inside the model.

And yeah, accessors are not a bad way to do that, I was just curious if there's a more automagical laravel way of doing that, since it's so common to need that.

So I imagined something like:

class Product extends Model
{
  protected $follow_foreign = ["top_color" => "name", "bottom_color" => "name", "side_color" => "name"];
}

Anyway, accessors are good enough, thanks for the replies.

Please or to participate in this conversation.