Relations
Relations in Larawiz are effortless. Just add the name of the relation, the type, and that's it. Larawiz will guess the target model from the relation name and add it to both the Model and the migrations, and also including their PHPDoc annotation.
yaml
models:
User:
posts: hasMany
Post:
title: string
user: belongsTo
1
2
3
4
5
6
2
3
4
5
6
php
/**
* @property-read \Illuminate\Database\Eloquent\Collection<int,\App\Models\Post>|\App\Models\Post[] $posts
*/
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
/**
* @property-read \App\Models\User $user
*/
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
php
Schema::create('posts', function (Blueprint $table) {
$table->foreignIdFor(User::class);
})
1
2
3
2
3
Alternatively, you can always set the name of the model, specially if you don't abide to Laravel naming conventions.
yaml
models:
User:
publications: hasMany:Post
Post:
author: belongsTo:User
1
2
3
4
5
2
3
4
5
php
/**
* @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\Post>|\App\Models\Post[] $publications
*/
class User extends Model
{
public function publications()
{
return $this->hasMany(Post::class);
}
}
/**
* @property-read \App\Models\User $author
*/
class Post extends Model
{
public function author()
{
return $this->belongsTo(User::class);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Primary Keys are required
Larawiz will break the wand if you make a relation to a Model without a primary key.