1 year ago

Retrieving Multiple Table Rows with common column

Posted 1 year ago by brysonreece

Hi there, I'm currently trying to retrieve a collection of DB records that all have a common column, but seem to be running into a few issues with Eloquent. For example, my models are set up as follows:


class ASensor extends Sensor { }


class BSensor extends Sensor { }


class CSensor extends Sensor { }


abstract class Sensor extends Model {

    public function container() {
        return $this->belongsTo(Container::class);


class Container extends Model {

    public function a_sensors() {
        return $this->hasMany(ASensor::class);
    public function b_sensors() {
        return $this->hasMany(BSensor::class);
    public function c_sensors() {
        return $this->hasMany(CSensor::class);

As you can see, each Sensor has a "container_id" column referencing the parent Container model. My problems arises when I try to implement an overall sensors method as follows:


    public function sensors() {
        $sensors = DB::table('a_sensors')
            ->join('b_sensors', 'b_sensors.container_id', 'a_sensors.container_id')
            ->join('c_sensors', 'c_sensors.container_id', 'b_sensors.container_id')
            ->where('container_id', '=', $this->id)
        return $sensors;

I (am attempting to and) would expect the above method would return a collection of ALL sensors that have the container_id equal to the current Container instance's ID. However, it only returns c_sensors that follow that pattern.

Any thoughts?

Please sign in or create an account to participate in this conversation.