发布Laravel关系

时间:2018-05-21 13:27:38

标签: php laravel orm

我有两个表usersnotes,我试图以某种方式与他们联系但是当我创建了我的hasManybelongTo脚本时在一定时间后不加载和超时。

我正在尝试创建一个基本的笔记添加系统,以便您可以在用户的​​帐户中添加笔记。我已经成功地与在其帐户上有笔记的用户建立了hasMany关系,但是,我正在尝试在notes上定义一个关系,通过创建该笔记的用户。{ p>

我的数据库布局如下:

用户:

`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']时,脚本崩溃并且根本不加载。

任何人都可以对此有所了解吗?

3 个答案:

答案 0 :(得分:1)

这是你要找的吗?

用户模型:

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",
     },
   }

答案 1 :(得分:-1)

  

注意模型

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);
    }
}

答案 2 :(得分:-1)

用户模型应为

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

和Notes模型

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

现在只需从notes实例中调用user()即可获取创建该笔记的用户的详细信息。