What do your migrations look like?
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.
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');
}
Please or to participate in this conversation.