I have two models A and B with a foreign key on A of b_id
on the id
of B. the model code is as follows
A has a trait BB with the following methods
public function b() // shared by multiple models
{
return $this->hasOne(B::class, 'id', 'b_id'); // table has foreign keys setup
}
public function saveB($params){
$b = $this->b;
if(is_null($b)) $b = new B;
else $b->a()->dissociate($b->id); // if there is a b break the link between them
if($b->setParams($params) === true)
{
try {
$this->b()->save($b);
$this->save();
} catch (Exceptio ....... throw an exception if anything
}
B is a model with the method
public method setParams($params) {
$this->trigger = $params[0];
$this->colour = $params[1];
.... arbitrary stuff not related;
}
The problem arises out of the following TestCase logic
public function setUp()
{
parent::setUp();
$this->a = A::find(237); // actual record
$this->a->saveB(['trigger'=>1,'colour'=>'orange']);
}
public function testSaveB(){
$this->assertGreaterThan(0, $this->a->b_id);
}
The assertGreaterThan test fails and the b_id is null even though the following is true
- The table foreign keys exists
- Appropriate fields are fillable
- The data for B is inserted( no previous record existed)
- The record exists and b_id was NULL from inception
- No exceptions are thrown
Note the model names have been changed to make things easier to understand but the functions are more or less exactly as I have it
Does this logic model->hasOne()->save(model)
inserts the newly created model and updates the foreign key for it? or do i have to still update the key/ value and $a->update() rather than $a->save()?