In SalesforceTest2, the 1'st parameter after the class should be the foreign key.
public function test1()
{
return $this->belongsTo('App\Models\SalesforceTest1', 'id', 'test1Id');
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I am testing one-to-many relationships and have come across a situation where I cannot figure out how to get data for a parent object from a child object.
pkid (primary key, auto increment)
Id (varchar)
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SalesforceTest1 extends Model
{
public $timestamps = false;
protected $connection = 'esb-salesforce';
protected $table = 'test1';
protected $primaryKey = 'pkid';
protected $guarded = [];
public function test2()
{
return $this->hasMany('App\Models\SalesforceTest2', 'test1Id', 'Id');
}
}
pkid (primary key, auto increment)
test1Id (varchar, foreign key to test1.Id)
name (varchar)
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SalesforceTest2 extends Model
{
public $timestamps = false;
protected $connection = 'esb-salesforce';
protected $table = 'test2';
protected $primaryKey = 'pkid';
protected $guarded = [];
public function test1()
{
return $this->belongsTo('App\Models\SalesforceTest1', 'test1Id', 'Id');
}
}
I have sample data in both tables.
test1
pkid: 1
Id: ab12345600k
test2
pkid: 1
test1Id: ab12345600k
name: John Doe
Executing the following works great and I get results as expected and can access test2:
>>> SalesforceTest1::where('Id','=','ab12345600k')->first()->test2;
=> Illuminate\Database\Eloquent\Collection {#680
all: [
App\Models\SalesforceTest2 {#705
pkid: 1,
test1Id: "ab12345600k",
name: "John Doe",
created_at: null,
updated_at: null,
},
],
}
But executing the following and trying to access test1, I get a null:
>>> SalesforceTest2::where('Test1Id','=','ab12345600k')->first()->test1;
=> null
What's interesting is even if I comment out the test1 method from SalesforceTest2, I still get a null instead of the collection I'd expect that contains:
pkid: 1
Id: ab12345600k
Table 1 > hasMany() > Table 2 Table 2 > hasOne() -> Table 1 (instead of belongsTo())
Please or to participate in this conversation.