gpt4 book ai didi

php - 我们如何在laravel中使用外键将数据从一个表插入到另一个表?

转载 作者:行者123 更新时间:2023-11-28 17:03:16 24 4
gpt4 key购买 nike

假设我有一个表(“附件”),另一个是表(“品牌”)。我想从品牌表中附加一个品牌标识,它将保存到表(“附件”)中。我是初学者提前抱歉。请帮我。\这是我的品牌 Controller ......

 public function create()
{
$brands = Brand::all();
$catagories = Catagory::all();
$attachments = Attachment::all();
return view('system-mgmt/brand/create', ['brands' => $brands, 'catagories' => $catagories,'attachments'=> $attachments]);

}

/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Catagory::findOrFail($request['catID']);
Attachment::findOrFail($request['attachmentID']);
$this->validateInput($request);
Brand::create([
'brandsName' => $request['brandsName'],
'attachmentID' => $request['attachmentID'],
'catID' => $request['catID']
]);

return redirect()->intended('system-management/brand');
}

这是我的 html 代码,这段代码是从附件表中获取数据...但我的要求是“数据将由用户插入”

 <div class="form-group">
<label class="col-md-4 control-label">Brand Logo</label>
<div class="col-md-6">
<select class="form-control" name="attachmentID">
@foreach ($attachments as $attachment)
<option value="{{$attachment->id}}">{{$attachment->attachmentName}}</option>
@endforeach
</select>
</div>
</div>

最佳答案

您想将一个表的数据插入另一个关系表不是最佳做法。
在这里你可以使用 join选择数据时查询并避免插入过程更好。

brands 表与 attachments 表连接起来,并在 外键 之后访问 brand_logo

//Please make sure your table and field name is correct   
$attachments = DB::table('attachments')
->leftJoin('brands', 'attachments.id', '=', 'brands.attachmentID')
->select('attachments.*','brands.brand_logo')
->first();

echo $attachments->brand_logo;

However some time need to copy on table data to others table in this purpose you can do this.

//Laravel DB raw insert query
\DB::insert("INSERT INTO table_a(fld_a,fld_b)
SELECT
fld_a,fld_b // Make sure select column same sequence of insert field name(fld_a,fld_b).
FROM
table_b
WHERE table_b.id > 100 //condition
");

详情 here .

关于php - 我们如何在laravel中使用外键将数据从一个表插入到另一个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51445953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com