Skip to content

Commit 30681b9

Browse files
committed
Add code
0 parents  commit 30681b9

File tree

4 files changed

+69
-0
lines changed

4 files changed

+69
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
vendor/
2+
composer.lock

composer.json

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"name": "stancl/laravel-hasmanywithinverse",
3+
"description": "Define HasMany while also setting the inverse relationship in Laravel.",
4+
"type": "package",
5+
"license": "MIT",
6+
"autoload": {
7+
"psr-4": {
8+
"Stancl\\HasManyWithInverse\\": "src/"
9+
}
10+
},
11+
"authors": [
12+
{
13+
"name": "Samuel Štancl",
14+
"email": "[email protected]"
15+
}
16+
],
17+
"require": {
18+
"illuminate/database": "^6.0|^7.0"
19+
}
20+
}

src/HasManyWithInverse.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
namespace Stancl\HasManyWithInverse;
4+
5+
trait HasManyWithInverse
6+
{
7+
public function hasManyWithInverse($related, $inverse, $foreignKey = null, $localKey = null)
8+
{
9+
$instance = $this->newRelatedInstance($related);
10+
11+
$foreignKey = $foreignKey ?: $this->getForeignKey();
12+
13+
$localKey = $localKey ?: $this->getKeyName();
14+
15+
return new HasManyWithInverseRelationship($instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey, $inverse);
16+
}
17+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
namespace Stancl\HasManyWithInverse;
4+
5+
use Illuminate\Database\Eloquent\Builder;
6+
use Illuminate\Database\Eloquent\Model;
7+
use Illuminate\Database\Eloquent\Relations\HasMany;
8+
9+
class HasManyWithInverseRelationship extends HasMany
10+
{
11+
protected string $relationToParent;
12+
13+
public function __construct(Builder $query, Model $parent, $foreignKey, $localKey, $relationToParent)
14+
{
15+
$this->relationToParent = $relationToParent;
16+
17+
parent::__construct($query, $parent, $foreignKey, $localKey);
18+
}
19+
20+
public function create(array $attributes = [])
21+
{
22+
return tap($this->related->newInstance($attributes), function ($instance) {
23+
$this->setForeignAttributesForCreate($instance);
24+
25+
$instance->setRelation($this->relationToParent, $this->getParent());
26+
27+
$instance->save();
28+
});
29+
}
30+
}

0 commit comments

Comments
 (0)