如何访问数据透视表的数据(多对多关系laravel)

时间:2020-02-02 05:46:24

标签: php laravel oop web

我正在尝试从数据透视表中获取数据,并将其传递给jquery ajax。我想得到这本书的名称和数量。

我的模特

String str = "Hello World. Hello Java.";
String[] tokens = str.split("\\s+");
String reverseString = "";
for (String token : tokens) {
    String reverse = "";
    for (int i = token.length() - 1; i >= 0; i--) {
        reverse = reverse + token.charAt(i);
    }
    if(reverse.charAt(0) == '.') {
        reverse = reverse.substring(1) + ".";
    }
    reverseString = reverseString + " " + reverse;
}
System.out.println(reverseString);

这是我的控制器

collision.gameObject

我不知道为什么返回

spawnwall

我的数据透视表(book_order)

class Order extends Model
{
    public function books(){
        return $this->belongsToMany(Book::class)->withPivot('quantity');
    }

}


class Book extends Model
{

    public function order(){
        return $this->belongsToMany(Order::class)->withPivot('quantity');
    }

}

2 个答案:

答案 0 :(得分:-1)

您可以使用以下方法从quantity数据透视表中检索book_order列:

class Order extends Model
{
    public function books(){
        return $this->belongsToMany(Book::class)
        ->withPivot([
            'quantity',
        ]);
    }
}


class Book extends Model
{
    public function order(){
        return $this->belongsToMany(Order::class)
        ->withPivot([
            'quantity',
        ]);
    }
}

用法

//Controller
public function detail($id){
   if($id){
      //Eager Load
      $orderWithBooks = Order::with('books')->find($id);
      foreach ($order->books as $book) {
         $quantity = $book->pivot->quantity;
         dump($quantity);
      }
   }
}

答案 1 :(得分:-1)

基本上,我假设您有这样的表:

**books** 
id 
name

**orders** 
id 

**quantity**
book_id
order_id 

型号:

class Order extends Model
{
    public function books(){
        return $this->belongsToMany(Book::class,'quantity');
    }

}

class Book extends Model
{

    public function orders(){
        return $this->belongsToMany(Order::class,'quantity');
    }

}

尝试建立这样的关系:

$books = $order->books()->get();