리소스 관계를 관리하는 방법

BelongsTo : 나는 속한다.

HasMany : 많은 관계를 맺는다.

BelongsToMany: 나는 여러개에 소속된다.


1. app/Post.php 소스에 들어가서 관계를 설정해준다.

1
2
3
4
5
    public function user()
    {
        // 나는 유저에게 속한다.
        return $this->belongsTo(User::class);
    }
cs


반대로 app/User.php 에게도 관계를 설정해준다.

1
2
3
4
5
    public function posts()
    {
        //나는 여러개의 post를 가지고 있습니다. 여기서 나는 user이다.
        $this->hasMany(Post::class);
    }
cs


2. app/Nova/Post.php  fields메서드로 가서 소스를 삽입해준다.


BelongsTo::make('User')


상단에 꼭 넣어주자(비주얼스튜디오코드에서 ctrl+speace 자동 임포트 된다.

1
use Laravel\Nova\Fields\BelongsTo;
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
 
            Text::make('Title')->sortable(),
 
            Trix::make('Body')->sortable(),
 
            DateTime::make('Publish At')->hideFromIndex(),
 
            DateTime::make('Publish Until')->hideFromIndex(),
 
            Boolean::make('Is Published'),
 
            Select::make('Category')->options([
 
                'tutorials' => 'Tutorials',
                'news' => 'News'
 
            ])->hideWhenUpdating(),
 
            BelongsTo::make('User')
 
        ];
    }
cs


목록에 user필드가 추가되었다.


그냥입력하면 에러가 뜰것이다. 컬럼추가 마이그레이션파을을 새로 만들어주자

1
php artisan make:migration --table=posts add_more2_post_columns
cs


스키마추가

1
2
3
4
5
6
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->unsignedInteger('user_id');
        });
    }
cs


마이그레이션실행

1
php artisan migrate
cs


db테이블을 확인해보면 user_id 컬럼이 생성되었다.


수정을 눌러서 user선택후 업데이트를 하면 적용이 된다.


User을 name값으로 변경하려고 하면 Nova/User.php

1
public static $title = 'name';
cs


값을 변경해주자 email or name


3. User 목록에서 유저를 클릭하면 유저가 작성한 Posts를 구현해보자


app/Nova/User.php 에서 HasMany::make('Posts') 추가하자

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
 
            Gravatar::make(),
 
            Text::make('Name')
                ->sortable()
                ->rules('required', 'max:255'),
 
            Text::make('Email')
                ->sortable()
                ->rules('required', 'email', 'max:254')
                ->creationRules('unique:users,email')
                ->updateRules('unique:users,email,{{resourceId}}'),
 
            Password::make('Password')
                ->onlyOnForms()
                ->creationRules('required', 'string', 'min:8')
                ->updateRules('nullable', 'string', 'min:8'),
 
            HasMany::make('Posts')
        ];
    }
cs


app/User.php

return(반환) 을 추가해주자


유저를 클릭하면 유저가 작성해놓은 글이 보일 것이다.


4. Tag resource를 만들어보자(마이그레이션,모델 파일 필수)

1
php artisan nova:resource Tag
cs


Nova디렉토리에 Tag.php파일이 생성되었다.


Tags마이그레이션 파일을 만들어주자

1
php artisan make:migration create_tags_table --create=tags
cs


스키마

1
2
3
4
5
6
7
8
    public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('tag');
            $table->timestamps();
        });
    }
cs


모델을 만들어주자(모델은 단수이다)

1
php artisan make:model Tag
cs


Tag라는 리소스가 등록되었다.


Nova/Tag.php 파일을 수정해주자

1
public static $title = 'tag';
cs


1
2
3
    public static $search = [
        'id','tag'
    ];
cs


필드를 추가하자

1
2
3
4
5
6
7
8
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
 
            Text::make('Tag')
        ];
    }
cs


Tag를 추가해보자


5. app/Post.php 에 관계를 설정하자.

1
2
3
4
5
    public function tags()
    {
        //나는 태그에 속한다.
        return $this->belongsToMany(Tag::class);
    }
cs


app/Tag.php 에 관계를 설정하자.

1
2
3
4
    public function posts()
    {
        return $this->belongsToMany(Post::class);
    }
cs


Nova/Post.php 에 필드를 추가하자

1
 BelongsToMany::make('Tags')
cs


여기서 엄청 해맸다 이후 되지가 않았기 때문이다


SQLSTATE[42s02]: Base table or view not found: 1146 Table ‘laravel nova.post_tag’ doesn’t exist(SQL:select `tags`.*,`post_id` as `pivot_post_id`,`post_tag`.`tag_id` as `pivot_tag_id` from `tags` inner join `post_tag` on `tags`.`id` = `post_tag`.`tag_id` where `post_tag`.`post_id` = 6 order by `tags`.`id` desc limit 6 offset(0)


해결방법>

테이블을 만들어준다. post_tag

1
php artisan make:migration create_post_tag_table
cs


테이블스키마

1
2
3
4
5
6
7
8
9
    public function up()
    {
        Schema::create('post_tag', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('post_id')->unsigned();
            $table->integer('tag_id')->unsigned();
            $table->timestamps();
        });
    }
cs


테이블이 생성되었으니 다시 실행해보자


우와~~ 된다.~~~ 8시간 까먹었다.  관계는 잘 이해가 가지 않는다. 연습을 많이 해봐야겠다.


6. Nova/Tag.php 파일에서 다음과 같이 소스를 field를 추가한다.

1
2
3
4
5
6
7
8
9
10
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
 
            Text::make('Tag'),
 
            BelongsToMany::make('Posts')
        ];
    }
cs


해당태그 디테일 클릭시 해당Posts 관계를 보여준다.


'라라벨 > NOVA' 카테고리의 다른 글

자원(resource)의 권한(Authorization) policy(정책)  (0) 2020.01.01
자원(resource)의 검증(vaildation)  (0) 2020.01.01
자원(resource)의 분야 field  (0) 2019.12.31
자원(resource)의 정의  (0) 2019.12.31
nova설치하기  (0) 2019.12.31

+ Recent posts