Laravel:查询多对多数据透视表

时间:2018-09-24 11:40:46

标签: php laravel

我有一个可以让用户拥有多本图书的应用程序。我已经建立了关系船和中介表。但是查询无法正常工作。

图书模型

    public function user(){
    return $this->belongsToMany('App\Book', 'book_user');
    }

用户模型

public function book(){
        return $this->belongsToMany('App\User', 'book_user');
    }

创建user_book表迁移:

  public function up()
    {
        Schema::create('book_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('book_id')->unsigned();
            $table->foreign('book_id')->references('id')->on('books');

            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

Books控制器我将book_id和用户_id添加到表中

   public function readlist(Book $book)
    {
        DB::table('book_user')->insert(
            ['user_id' => auth()->id(), 
            'book_id' => request('book_id')]
        );

    }

在我的家庭控制器中,我尝试访问与用户相关的书籍,但结果返回Null;

 public function index()
{   
    $user = Auth::user();
    $userbooks =$user->books;
    dd($userbooks);

    return view('/home');
}

2 个答案:

答案 0 :(得分:0)

首先在您的用户模型中将您的 LinkedList<String[]> llist = new LinkedList <> (); String in0[] = new String[3]; llist.add(in0); String in1[] = new String[3]; in1[0] = "1"; in1[1] = "testtest"; in1[2] = "IND"; llist.add(in1); String[] data; FileOutputStream outstream = new FileOutputStream( "C:\\Users\\Desktop\\data.xls"); Xcelite xcelite = new Xcelite(); XceliteSheet sheet = xcelite.createSheet("Clean"); SheetWriter writer = sheet.getBeanWriter(Entity.class); List<Entity> entities = new ArrayList<>(); for (int i = 0; i < llist.size(); i++) { if (i == 0) { System.out.println("Hello World!"); } else { data = llist.get(i); String ccode1 = data[2]; String replace; if (data[2].equals("IND")) { replace = data[2].replaceAll("IND", "IN"); ccode1 = replace; } else if (data[2].equals("USA")) { replace = data[2].replaceAll("USA", "US"); ccode1 = replace; } else { ccode1 = data[2]; } Entity entity = new Entity(); entities.add(entity); entity.empid1 = data[0]; entity.fname = data[1]; entity.ccode1 = ccode1; } } writer.write(entities); xcelite.write(outstream); } 方法重命名为book():)

然后您可以尝试执行以下操作:

books()

答案 1 :(得分:0)

用户有多本图书

书有多个用户,

这种关系是多对多, 最好定义用户模型:

public function users(){
  return $this->belongsToMany('App\Book', 'book_user');
}

在您的Book模型中

public function books(){
    return $this->belongsToMany('App\User', 'book_user');
}

文档链接:https://laravel.com/docs/5.7/eloquent-relationships#many-to-many