laravel 關聯模型


官方文檔5.5:https://laravelacademy.org/post/8203.html

一對一   hasone  (用戶-手機號)

一對多   hasmany(文章-評論)

一對多反向 belongsto (評論-文章)

多對多  belongstomany (用戶-角色)

遠層一對多  hasmanythrough  (國家-作者-文章)

多態關聯  morphmany  (文章、視頻-評論)

多態多對對  morphtomany  (文章、視頻-標簽)

//post模型  文章表的模型層
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $guarded = [];

    //關聯user(用戶)模型
    public function user()
    {
        return $this->belongsTo('App\User');//如果按照laravel中規定的定義的,后面兩個參數可以忽略,
     //return $this->belongsTo('App\User','user_id','id');//user_id為外鍵
} //在文章的模型層中寫的,用戶和文章是一對多,所以文章和用戶是一對多反向,使用   belongsto }


//關聯comment模型
    public function comments()
    {
        return $this->hasmany('App\comment')->orderBy('created_at','desc');
    }
//controller
//添加評論
public function comment(Post $post)
    {
        $this->validate(request(),[
            'content'=>'required|min:3'
        ]);
        $comment = new Comment();
        $comment->user_id = Auth::id();
        $comment->content = request('content');
        $comment->post_id = $post->id;
        $post->comments()->save($comment);//也可以使用以前的添加
        return back();//返回上一個頁面
    }
//評論的模型層需要關聯user
public function user()
{
     return $this->belongsTo('App\User');
}
//可以在controller中進行預加載 $post->load('comments');  其余不變,知識view不用進行加載了
//view
<ul class="list-group"> @foreach($post->comments as $comment) <li class="list-group-item">            
        <h5>{{$comment->created_at}} by {{$comment->user->name//注意user不能加()
        <div> {{$comment->content}} </div>                              
    </li> @endforeach                             
</ul>                                       

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM