簡體   English   中英

發行Laravel關系

[英]Issue Laravel Relationships

我有兩個表usersnotes ,我試圖以某種方式與它們相關聯,但是當我創建了hasManybelongTo ,腳本不會加載並且在一定時間后超時。

我正在嘗試創建一個基本的便箋添加系統,以便您可以將便箋添加到用戶的帳戶中。 我已經成功建立了hasMany關系到在其帳戶上具有注釋的用戶,但是,我正在嘗試在notes上定義一種關系,該關系會帶給創建注釋的用戶。

我的數據庫布局如下:

使用者:

`id`, `username`, `password`

1   , Connor    , hash

筆記:

`id`, `note`, `user_id`, `user_id_created`

1   , Hello ,  1       , 1

因此,這意味着user ID 1已經針對他們自己創建了一個注釋,因此在我的用戶模型中,我使用:

class User { 
    public function notes(){
        return $this->hasMany("App\Note");
    }
    public function created_notes(){
        return $this->hasMany("App\Note", "id", "user_id_created");
    }
}

然后在我的Notes模型中使用:

class Note {
    protected $with = ['created_by']
    public function created_by(){
        return $this->belongsTo("App\User", "user_id_created", "id");
    }
}

但是,當我完成此操作並嘗試在Note的模型上使用$with = ['created_by']時,腳本將崩潰並且根本不會加載。

誰能對此有所啟發?

這是您要找的東西嗎?

用戶模型:

class User extends Authenticatable
{
    public function notes(){
        return $this->hasMany("App\Note");
    }
    public function created_notes(){
        return $this->hasMany("App\Note", "id", "user_id_created");
    }
}

筆記型號:

use Illuminate\Database\Eloquent\Model;

class Note extends Model {
    protected $with = ['created_by'];

    public function created_by()
    {
        return $this->belongsTo("App\User", "user_id_created", "id");
    }
}

修補匠結果:

>>> $note = App\Note::find(1)
=> App\Note {#771
     id: 1,
     note: "1",
     user_id: 1,
     user_id_created: 1,
     created_at: "2018-05-21 08:58:32",
     updated_at: "2018-05-21 08:58:32",
     created_by: App\User {#778
       id: 1,
       name: "bob",
       email: "bob@example.com",
       created_at: "2018-05-21 08:58:22",
       updated_at: "2018-05-21 08:58:22",
     },
   }

音符模型

class Note extends Model
{

    protected $table='notes';
    public $primaryKey='id';
    protected $fillable = ['id','note','user_id','user_id_created'];

    public function user(){
        return $this->belongsTo('App\User','user_id');
    }

}

用戶模型

class User extends Authenticatable
{
    use Notifiable;

    protected $table='users';
    public $primaryKey='id';

    protected $fillable = ['username'];
    protected $hidden = ['password'];


    public function posts(){
        return $this->hasMany('App\Post');
   }
}

在您的控制器中

use App\Note;
use Illuminate\Http\Request;

class NotesController extends Controller
{

    public function get_notes(Request $request){
      $notes=Note::with('user')->orderBy('created_at','desc')->get();
      return response()->json($notes);
    }
}

用戶模型應為

class User { 
    public function notes(){
        return $this->hasMany(Note::class);
    }
}

和筆記模型

class Note {
    public function user(){
        return $this->belongsTo(User::class);
    }
}

現在,只需從notes實例調用user()即可獲取創建注釋的用戶的詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM