我有一对多的产品与书籍的关系。
我的控制器中的功能:
public function editProduct($p_id)
{
$books = Product::findOrFail($p_id);
return view('master.editProduct')->with(['books'=>$books]);
}
editProduct.blade.php
<!--Returns Name from product table-->
<div class="form-group">
<label>Book Title</label>
<input type="text" class="form-control" name="name" value = "{{ $books->name }}">
</div>
<!--Should return author from books table-->
<div class="form-group">
<label>Author</label>
<input type="text" class="form-control" name="author" " value = "{{ $books->books->author }}">
</div>
我也尝试过:
$books->books
返回了p_id $books->books->author
仅从books表中获取作者但返回错误。我收到错误:此集合实例上不存在属性[author]。
如何在我看来从书籍表中获得作者的价值?产品型号
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $tables= "products";
protected $primaryKey = 'product_id';
public $incrementing = false;
protected $fillable = ['product_id','product_type','name', ...,];
protected $hidden =['created_at', 'updated_at'];
public function books(){
return $this->hasMany('App\Book', 'product_id');
}
}
预订模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
protected $tables= "books";
protected $fillable = ['product_id','author', 'edition',...];
protected $hidden =['created_at', 'updated_at'];
public function products(){
return $this->belongsTo('App\Product');
}
}
EditForm字段
标题存储在Products表中,我可以在表单中访问
<div class="form-group">
<label>Book Title</label>
<input type="text" class="form-control" name="name" value = "{{ $books->name }}">
</div>
在同一表格中,不会访问作者。
答案 0 :(得分:1)
两个查询解决方案:
$books = Product::find($p_id)->books()->get();
一个查询解决方案:
$books = Book::where('product_id', $p_id)->get();
显示数据:
@foreach ($books as $book)
{{ $book->name }}
@endforeach
答案 1 :(得分:0)
{{1}}
答案 2 :(得分:0)
的ProductsController
public function editProduct($p_id){
$products = Product::with(['books'])->where('product_id', $p_id)->get();
return view('master.editProduct', compact('products'));
}
查看 我在表单中使用了两个foreach循环来访问产品表中的名称和书表中的作者,如下所示:
@foreach($products as $product)
<form>
...
<div class="form-group">
<label>Book Title</label>
<input type="text" class="form-control" id="name" name="name" value = "{{ $product->name }}">
</div>
@foreach($product->books as $books)
<div class="form-group">
<label>Author</label>
<input type="text" class="form-control" id="author" name="author" " value = "{{ $books->author }}">
</div>
@endforeach
...
</form>
@endforeach