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

mattnewark's avatar

belongsTo

Good Morning all,

I am trying to get details from another DB using belongsTo in eloquent but I can't seem to get it to to work.

I have two DB's one that is called tickets and has the column tcode_id and the other one is tcodes and has id and description.

What I need to do is show the description that is related to the id that is in the tickets db.

My Ticket model is like the below:

public function tcodes()
    {
      return $this->belongsTo(Tcode::class);
    }

My Tcode model is below:

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

My controller is:

public function show($id)
    {
        $tickets = Ticket::where('site_id', $id)
                          ->orderBy('time_created', 'desc')
                          ->limit(5)
                          ->get();
        $sites = Site::findOrFail($id);
        $service = $sites->services()->paginate(5);
        return view('site.show')
              ->with([
                'sites' => $sites,
                'service' => $service,
                'tickets' => $tickets
              ]);
    }

and the view:

@foreach ($tickets as $ticket)
                          <tr>
                            <td>{{ $ticket->id }}</td>
                            <td>{{ date('d-M-Y H:i', strtotime($ticket->time_created)) }}</td>
                            <td>{{ $ticket->owner }}</td>
                            <td>{{ $ticket->tcodes->description }}</td>
                            <td><a href="" class="btn btn-sm btn-info pull-left" style="margin-right: 3px;">Details</a></td>
                          </tr>
                        @endforeach 

I have added the $ticket->tcodes->description should show the description that is related to the id that is on the tickets db.

What am I doing wrong?

Thanks in advance.

0 likes
34 replies
mattnewark's avatar

Hi @zachleigh,

public function up()
    {
        Schema::create('tcodes', function (Blueprint $table) {
            $table->integer('id');
            $table->string('description');
        });
    }

public function up()
    {
        Schema::create('tickets', function (Blueprint $table) {
            $table->increments('id');
            $table->datetime('closed');
            $table->string('closed_by');
            $table->integer('tcode_id');
            $table->text('other_desc');
            $table->integer('company_id');
            $table->integer('site_id');
            $table->integer('service_item_id');
            $table->text('description');
            $table->integer('status');
            $table->string('owner');
            $table->datetime('time_created');
            $table->string('updated_by');
            $table->datetime('time_updated');
            $table->string('purchase_order_no');
        });
zachleigh's avatar

Try reversing your relationship methods.

Ticket:

public function tcodes()
{
    return $this->hasOne(Tcode::class);
}

Tcode:

public function tickets()
{
    return $this->belongsTo(Ticket::class);
}
mattnewark's avatar

Hi,

I have made the change and this is error I get:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tcodes.ticket_id' in 'where clause' (SQL: select * from `tcodes` where `tcodes`.`ticket_id` = 180184 and `tcodes`.`ticket_id` is not null limit 1) (View: C:\xampp\htdocs\zone\resources\views\site\show.blade.php)

I don;t want ti to look for the ticket_id, I need it to look t the ticket table and then find the tcode_id and then look in the tcodes table and find the corresponding description for that id..

Thanks

zachleigh's avatar

Were you getting an error before? What was wrong with it?

mattnewark's avatar

Hi,

Yes I was:

Trying to get property of non-object (View: C:\xampp\htdocs\zone\resources\views\site\show.blade.php)

and this was for the line:

<td>{{ $ticket->tcodes->description }}</td>
zachleigh's avatar

Probably because if there is no tcode for a ticket, $ticket->tcodes returns null.

mattnewark's avatar

Hi, I have checked the db and all rows have a tcode_id in the tickets table and I have checked the tcode table for the id and it has one.

Parasoul's avatar

Try this to find the missing tcodes

<td>{{ $ticket->tcodes ? $ticket->tcodes->description : 'No tcode'}}</td>

instead of

<td>{{ $ticket->tcodes->description }}</td>
mattnewark's avatar

I get 'No tcode' in the table. So does that mean that it is using the ticket id and not the number from the tcode_id column from the ticket table? How do I get the tcode_id and then find the description of the tcode from the tcode table?

Thanks in advance

Parasoul's avatar

I don't see anything wrong in the code. Are you sure tcode_id in your tickets have a corresponding id in the tcodes tables?

mattnewark's avatar

Hi, Neither can I, there is obviously something wrong somewhere.

So just to recap, the tcodes table has two columns, id & description. The id should correspond to the column that is in the tickets table that is called tcode_id. All the rows have a tcode_id in the icket table that is the same as the id in the tcodes table.

If I do the below:

{{ $ticket->tcode_id }}

it brings though the tcode_id with no issues. is there something in my models that is not working correctly for the join?

Parasoul's avatar

Try in your controller

dd(Tcodes::find($tickets->first()->tcode_id));
mattnewark's avatar

Could you please tell me where as I get an error:

$tickets = Ticket::where('site_id', $id)
                          ->orderBy('time_created', 'desc')
                          ->limit(5)
                          ->get();
        $sites = Site::findOrFail($id);
        $service = $sites->services()->paginate(5);
        return view('site.show')
              ->with([
                'sites' => $sites,
                'service' => $service,
                'tickets' => $tickets
              ]);

Just to make you aware that the model is Tcode.

Thanks

mattnewark's avatar
Tcode {#321 ▼
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:2 [▼
    "id" => 2
    "description" => "Missed lift"
  ]
  #original: array:2 [▼
    "id" => 2
    "description" => "Missed lift"
  ]
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #events: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [▼
    0 => "*"
  ]
}
zachleigh's avatar

How about this:

foreach (Tickets::all() as $ticket) {
    var_dump($ticket->tcode_id);
}

dd('finished');

Did all the tickets have a tcode instance?

mattnewark's avatar

Hi @zachleigh

This is what I get:

int(2) int(118) int(15) int(15) int(15) int(5) int(5) int(5) int(131) int(142) int(2) int(15) int(5) int(5) int(15) int(15) int(2) int(118) int(2) int(136) int(142) int(2) int(2) int(118) int(2) int(2) int(5) int(2) int(133) int(5) int(131) int(2) int(131) int(2) int(5) int(2) int(2) int(5) int(2) int(2) int(2) int(5) int(2) int(5) int(131) int(142) int(15) int(5) int(2) int(118) int(5) int(141) int(144) int(2) int(5) int(118) int(15) int(2) int(15) int(5) int(15) int(102) int(124) int(2) int(5) int(131) int(5) int(2) int(131) int(102) int(131) int(2) int(118) int(5) int(102) int(118) int(102) int(5) int(2) int(125) int(2) int(131) int(131) int(3) int(2) int(2) int(2) int(5) int(5) int(2) int(15) int(5) int(102) int(5) int(5) int(2) int(15) int(5) int(125) int(2) int(125) int(125) int(125) int(125) int(112) int(112) int(5) int(2) int(112) int(2) int(131) int(131) int(125) int(125) int(125) int(125) int(15) int(112) int(5) int(112) int(137) int(137) int(137) int(112) int(5) int(15) int(102) int(15) int(5) int(131) int(131) int(5) int(2) int(15) int(5) int(15) int(15) int(2) int(2) int(2) int(2) int(5) int(15) int(5) int(2) int(15) int(5) int(15) int(133) int(102) int(2) int(2) int(15) int(2) int(15) int(133) int(133) int(5) int(2) int(2) int(2) int(2) int(2) int(2) int(133) int(15) int(2) int(1) int(2) int(15) int(131) int(2) int(2) int(2) int(102) int(15) int(15) int(131) int(2) int(2) int(5) int(15) int(2) int(5) int(2) int(2) int(2) int(5) int(2) int(2) int(15) int(2) int(2) int(118) int(125) int(2) int(2) int(2) int(5) int(5) int(102) int(15) int(2) int(2) int(2) int(2) int(5) int(2) int(2) int(131) int(131) int(2) int(2) int(2) int(2) int(131) int(3) int(2) int(131) int(131)
"finished"
mattnewark's avatar

So, When I add the below I get an SQLSTATE error and it is looking for the ticket_id in the tcodes table which there isn't.

{{ $ticket->tcodes->description }}

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tcodes.ticket_id' in 'where clause' (SQL: select * from `tcodes` where `tcodes`.`ticket_id` = 180184 and `tcodes`.`ticket_id` is not null limit 1) (View: C:\xampp\htdocs\zone\resources\views\site\show.blade.php)

So how can I change what is being looked for and for which table. I need it to look at the tickets table and find the tcode_id and then look for the id in the tcodes table..

Parasoul's avatar

Try this:

foreach (Tickets::all() as $ticket) {
    dump(Tcode::find($ticket->tcode_id));
}

dd('finished');
mattnewark's avatar

Hi @Parasoul,

All the rows appear and the below is the first two:

Tcode {#515 ▼
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:2 [▼
    "id" => 2
    "description" => "Missed lift"
  ]
  #original: array:2 [▼
    "id" => 2
    "description" => "Missed lift"
  ]
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #events: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [▶]
}
Tcode {#512 ▼
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:2 [▼
    "id" => 118
    "description" => "Service Day Change"
  ]
  #original: array:2 [▼
    "id" => 118
    "description" => "Service Day Change"
  ]
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #events: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [▶]
}
Parasoul's avatar
Parasoul
Best Answer
Level 3

Ok, maybe your Tcode migration is wrong then.

You have to define the id as your primary key:

public function up()
    {
        Schema::create('tcodes', function (Blueprint $table) {
            $table->integer('id');
            $table->string('description');
        });
    }

//To 

public function up()
    {
        Schema::create('tcodes', function (Blueprint $table) {
            $table->integer('id')->primary();
        //you should also add ->unsigned() on all id and fk
            $table->string('description');
        });
    }

If it doesn't work try to change the relations

public function tcodes()
{
      return $this->belongsTo(Tcode::class, 'tcode_id', 'id');
}

public function tickets()
{
    return $this->hasOne(Ticket::class, 'tcode_id', 'id');
}

mattnewark's avatar

Hi @Parasoul,

I have changed as requested and I am still getting an error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tcodes.tcode_id' in 'where clause' (SQL: select * from `tcodes` where `tcodes`.`tcode_id` = 180184 and `tcodes`.`tcode_id` is not null limit 1)

It is saying that the tcode_id = 180184 which is incorrect, that is the ticket id.

it doesn't seem to be sending the tcode_id..

Parasoul's avatar

I did edit my relation (bad copy ^^). Retry with the new change.

Parasoul's avatar

Glad it worked. I think i know why it diddn't worked. I get my head in the code. So for the belongsTo he search for the corresponding relation in the other model. He was probably looking at tcodes_id.

Can you try this :

public function tcode()
{
      return $this->belongsTo(Tcode::class);
}

public function ticket()
{
    return $this->hasOne(Ticket::class);
}

It also might be because you have a function getKeyName in your model.

mattnewark's avatar

Hi @Parasoul,

When I remove 'tcode_id', 'id' from both ticket and tcode models I get an error. put it back and it works a treat.

Thanks

Parasoul's avatar

Did you change the name of the function to singular?

mattnewark's avatar

Hi, I have now and that has worked as well, so moving forward should I make sure that I make the functions singular?

Thanks

Next

Please or to participate in this conversation.