我想从数据库中获取记录(一对多)。但它只为我提供了产品表数据
表格结构
我的模特
namespace App;
use Illuminate\Database\Eloquent\Model;
class brand extends Model
{
protected $table="brand";
protected $primaryKey = 'brand_id';
public function product(){
return $this->belongsTo('App\product','brand_id','brand_id');
}
}
我的控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\brand;
class BrandController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$val=brand::with('product')->find(5)->product;
foreach($val as $va){
echo print_r($val);
}
}
它为我提供了产品表中的记录,但没有提供两个表
答案 0 :(得分:0)
由于品牌有很多产品且产品属于品牌,因此关系必须为select regexp_replace('/keywordonea/keywordtwob/393r-mr49 j5n65_9e8e77g77b8/keywordthreea','[0-9\/_.,!?-]','');
而不是hasMany()
:
belongsTo()
答案 1 :(得分:0)
您正在提取only
产品,删除产品部分以获取两者:
$val=brand::with('product')->find(5);
然后获得brand_name
-
$brand_name = $val->brand_name;
foreach($val->product as $product){
$prod_fault = $product->prod_fault;
}
不要忘记@alexey mezenin说,在你的hasMany()
模型中建立Brand
关系 -
public function product(){
return $this->hasMany('App\product','brand_id','brand_id');
}
答案 2 :(得分:0)
产品型号
public function brands()
{
return $this->hasMany(Brand::class);
}
品牌模型
public function product()
{
return $this->belongsTo(Product::class);
}
BrandController索引方法
public function index()
{
$brand = Brand::with('product')->find(1);
echo ($brand);
}
Out Put:
{"id":1,"name":"Toyota","product_id":1,"created_at":"2018-02-05 00:00:00","updated_at":"2018-02-05 00:00:00","product":{"id":1,"name":"Car","created_at":"2018-02-05 00:00:00","updated_at":"2018-02-05 00:00:00"}}
进一步审查 Guide for using Eloquent ORM with laravel by scotch.io 另一个链接 Laravel Eloquent Relationships from laravel documentation