如何在laravel 8中使用复合主键? [英] How to use composite primary key in laravel 8?

查看:66
本文介绍了如何在laravel 8中使用复合主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有使用迁移文件,因为我在数据库中有预先存在的表,我想知道如何强制 Laravel 使用我的复合主键.如果有任何方法可以覆盖.复合主键是 (Tel + number_str )这是我在模型中的功能:

I didn't use the migration files because I have preexisting tables in the database, I want to know how to force laravel to use my composite primary key.if there is any method to override. The composite primary key is (Tel + number_str ) This is my function in the model :

public function saveData(){
  $response = new ResponseModel(); 
                //Primary key(Tel + number_str )
                $reponse->Tel = '0123456789';//---> the first key
                $reponse->number_str = '1'; //---> the second key
    
                $reponse->view = '0';  
                $reponse->channal = '0';
                $reponse->save();
}

当我执行我有这个错误:

when I execute I have this error:

Yajra\Pdo\Oci8\Exceptions\Oci8Exception
Error Code : 904 
Error Message : ORA-00904: "ID": invalid identifier Position : 98 Statement : insert into "RESPONSE" ("TEL", "number_str", "view", "channal ") values (:p0, :p1, :p2, :p3) returning "ID" into :p4 Bindings : [0123456789,1,0,0,0]

推荐答案

Laravel 附带 Eloquent ORM,而 Eloquent 不支持复合键.如果您打算覆盖 Eloquent 方法以支持它们,则需要覆盖很多核心方法以保持一切正常工作.

Laravel ships with the Eloquent ORM, and Eloquent doesn't support composite keys. If you're aiming to override Eloquent methods in order to support them, you'll need to override a lot of core methods to keep everything working properly.

现在,Eloquent 不是与数据库交互的唯一选择.您仍然可以使用查询生成器来执行您的操作.但当然没有 ORM 的好处.

Now, Eloquent isn't the only option to interact with the database. You can still use the Query Builder to perform your operations. But of course without the benefits of an ORM.

DB::table('response')->insert([
    'tel' => '0123456789', 
    'number_str' => 1,
    'view' => 0,
    'channel' => 0,
]);

DB::table('response')
  ->where('tel', '0123456789')
  ->where('number_str', 1)
  ->get();

这篇关于如何在laravel 8中使用复合主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆