on delete cascade laravel - mysql

Morning everyone,
I have foreign keys set to on delete cascade in laravel 5 and mysql on a couple of tables where the existence of a employee depends on the existence of the country he was born in.
$table->foreign('id_estado_municipio')
->references('id_estado_municipio')
->on('cat_municipios')
->onDelete('cascade')
->onUpdate('cascade');
Problem is when I delete the country, the employee that must get erased along with it, gets erased from the database, but the employee's record keeps on showing at the index view.
Have tried setting engine to InnoDB in the config file, model observers to delete dependents but still can't figure out how to make it work.
Hopefully someone can give some light. It would be very much appreciate it.
Here you are my models and modelcontrollers
class Municipio extends Model
{
//
protected $table = 'cat_municipios';
protected $primaryKey = 'id_estado_municipio';
...
public function trabajadores()
{
return $this->hasMany(Trabajador::class,'id_trabajador');
}
protected static function boot() {
parent::boot();
static::deleting(function($municipio) {
// delete related stuff ;)
$municipio -> trabajadores() -> delete();
});
}
class MunicipioController extends Controller
{
...
public function destroy($id)
{
//
$municipio = Municipio::findOrFail($id);
$municipio -> trabajadores() -> delete();
$destruido = Municipio::destroy($id);
if($destruido)
return redirect()->route('Municipio.index')->with('info','Municipio eliminado con éxito.');
else
return redirect()->route('Municipio.index')->with('error','Imposible borrar Municipio.');
}
}
////////////////////////////////////////
class Trabajador extends Model
{
//
protected $table = 'trabajadors';
protected $primaryKey = 'id_trabajador';
...
public function municipio()
{
return $this->belongsTo(Municipio::class,'id_estado_municipio');
}
...
}
class TrabajadorController extends Controller
{
public function index()
{
//
$criterio = \Request::get('search'); //<-- we use global request to get the param of URI
$estadosciviles = EstadoCivil::orderBy('id_estado_civil')->paginate(50);
$estados = Estado::orderBy('id_estado') -> paginate(50);
$municipios = Municipio::orderBy('id_estado_municipio')->paginate();
$religiones = Religion::orderBy('id_religion')->paginate();
$trabajadores = Trabajador::where('nombre', 'like', '%'.$criterio.'%')
->orwhere('id_trabajador',$criterio)
->orwhere('a_paterno',$criterio)
->orwhere('a_materno',$criterio)
->orwhere('curp',$criterio)
->orwhere('rfc',$criterio)
->orwhere('seguro_social',$criterio)
->sortable()
->orderBy('id_trabajador')
->orderBy('nombre')
->paginate();
return view('Trabajador.index', array('trabajadores' => $trabajadores,'estadosciviles' => $estadosciviles,'estados' => $estados,'municipios' => $municipios,'religiones' => $religiones));
}
...
}

Related

Save data in 2 different tables with laravel

how can i save a record in 2 different tables.
I have my article model and my article controller in this way. My second table is called History
I hope you can help me, thank you very much
my article model:
protected $fillable =[
'idcategoria','codigo','nombre','precio_proveedor','precio_venta','iva','ieps','stock','stock1','descripcion','condicion'
];
public function categoria(){
return $this->belongsTo('App\Categoria');
}
my article controller, store method:
protected static function boot()
{
parent::boot();
// this triggers everytime an Article model is saved
static::saved(dd($articulo) { dd($article);
$historial = new Historial();
$historial->nombre = $articulo->nombre;
$historial->precio_proveedor = $articulo->precio_proveedor;
$historial->stock = $articulo->stock;
$historial->save();
});
}
In my history table I only need to save nombre, precio_proveedor,
stock
You can use observers for this. Add this in your Article model:
protected static function boot()
{
parent::boot();
// this triggers everytime an Article model is saved
static::saved(function (Article $article) {
$history = new History();
$history->nombre = $article->nombre;
$history->precio_proveedor = $article->precio_proveedor;
$history->stock = $article->stock;
$history->save();
});
}
Reference: https://www.larashout.com/how-to-use-laravel-model-observers

Laravel 5.8 show data of the another table like join

I need how to show data in another table like MySQL join or something like that
MySQL example
My Code
Model usuarios
class Usuario extends Model {
protected $table = 'usuarios';
protected $primaryKey = 'idusuarios';
protected $filliable = [
'cedula', 'nombre', 'tele1', 'tele2', 'correo', 'direccion',
'user_name', 'user_pass', 'fecha_ingreso', 'usu_idrol'
];
public function Usuario() {
return $this->hasOne('app\Roles','idrole','usu_idrol','desc_rol');
}
const CREATED_AT = NULL;
const UPDATED_AT = NULL;
}
Model Roles
class Roles extends Model {
protected $table ='roles';
protected $primarykey = 'idrole';
protected $filliable = ['desc_rol'];
public function Roles() {
return $this->belongsTo('app\Usuario', 'usu_idrol', 'idrole');
}
}
Controller usuarios
public function index(Request $request) {
if (!$request->ajax()) return redirect('/');
$usuarios = Usuario::all();
return $usuarios;
}
View usuarios
that's what I need
Try this in the controller that is returning data to your vue instance
//get all the users from the database (in your controller)
//you need to create a new array so as to easily map the role in the returned results
return Usuario::with('Usuario')->get()->map(function($role) {
return [
'field1' => $role->field1,
'field2' => $role->field2,
'field3' => $role->field3,
'field4' => $role->field4,
'field5' => $role->field5,
'rol' => $role->Usuario->desc_role
];
});

Yii2 model save returns true but there is no change in MySQL

Actually, If I update my model in the action of controller(in this case it is actionTest) it gets updated. Here is my code:
public function actionTest()
{
$model = ProviderOrder::find()->where(['is_used' => 0,'type' => Transaction::COD])->orderBy(['id' => SORT_ASC])->one();//const COD = 0
$model->is_used = 1;
$model->save();
}
But in my case I defined afterSave function to my Booking model. There I call getTrackNumber function which has Transaction Class in its body.
class Booking extends ActiveRecord
{
public function afterSave($insert, $changedAttributes)
{
$this->getTrackNumber($this->id);
parent::afterSave($insert, $changedAttributes);
}
public static function getTrackNumber($bookingId){
$transaction = new Transaction();
....
}
}
Inside of Transaction class there is the same code like in actionTest.
But the problem is $model->save() returns true but when I look through phpmyadmin there is no any change is_used is still 0.
But in the first case, i.e. in actionTest everything is fine. Please help me!

Method chainning for join table with pagination on CI 3

I create a core class named MY_Model that extends CI_Model. In this class, I create a method chaining to get all record with pagination like this :
// Take record with paging.
public function get_all_paged()
{
// get argument that passed
$args = func_get_args();
// get_all_paged($offset)
if (count($args) < 2) {
$this->get_real_offset($args[0]);
$this->db->limit($this->_per_page, $this->_offset);
}
// get_all_paged(array('status' => '1'), $offset)
else {
$this->get_real_offset($args[1]);
$this->db->where($args[0])->limit($this->_per_page, $this->_offset);
}
// return all record
return $this->db->get($this->_tabel)->result();
}
So , I just used like this on my controller,
for example
public function index($offset = NULL) {
$karyawan = $this->karyawan->get_all_paged($offset); //get all
}
I am realy confuse to get all record using join, I know join in CI like this :
public function get_all_karyawan() {
$this->db->select('tb_1 , tb_2');
$this->db->from('tb_1');
$this->db->join('tb_2', "where");
$query = $this->db->get();
return $query->result();
}
How to make it into chain in MY_Model?
Any help it so appreciated ...
The good thing in query builder, you can chain your db methods, till get(). So you can define, selects, where queries, limits in different ways.
For example:
public function category($category)
{
$this->db->where('category_id', $category);
return $this;
}
public function get_posts()
{
return $this->db->get('posts')->result();
}
And you can get all posts:
$this->model->get_posts();
Or by category:
$this->model->category(2)->get_posts();
So upon this, in your model:
public function get_all_karyawan() {
$this->db->select('tb_1 , tb_2');
$this->db->join('tb_1', "where");
// Here you make able to chain the method with this
return $this;
}
In your controller:
public function index($offset = NULL) {
$karyawan = $this->karyawan->get_all_karyawan()->get_all_paged($offset);
}

Why does adding a constructor fail this MSpec test with System.InvalidOperationException?

I have this first version of a class
public class GenerateAuthorisationWorkflows : IGenerateAuthorisationWorkflows
{
public IList<Guid> FromDtaObjects(IList<DtaObject> dtaObjects, Employee requestingEmployee)
{
foreach (var dtaObject in dtaObjects) { }
return new List<Guid>();
}
public IList<Guid> FromDtaObjects()
{
return new List<Guid>();
}
}
And the MSpec tests for it
public abstract class specification_for_generate_workflows : Specification<GenerateAuthorisationWorkflows>
{
protected static IWorkflowService workflowService;
Establish context = () => { workflowService = DependencyOf<IWorkflowService>(); };
}
[Subject(typeof(GenerateAuthorisationWorkflows))]
public class when_generate_workflows_is_called_with_a_dta_object_list_and_an_employee : specification_for_generate_workflows
{
static IList<Guid> result;
static IList<DtaObject> dtaObjects;
static Employee requestingEmployee;
Establish context = () =>
{
var mocks = new MockRepository();
var stubDtaObject1 = mocks.Stub<DtaObject>();
var stubDtaObject2 = mocks.Stub<DtaObject>();
var dtaObjectEnum = new List<DtaObject>{stubDtaObject1,stubDtaObject2}.GetEnumerator();
dtaObjects = mocks.Stub<IList<DtaObject>>();
dtaObjects.Stub(x => x.GetEnumerator()).Return(dtaObjectEnum).WhenCalled(x => x.ReturnValue = dtaObjectEnum);
requestingEmployee = mocks.Stub<Employee>();
mocks.ReplayAll();
};
Because of = () => result = subject.FromDtaObjects(dtaObjects, requestingEmployee);
It should_enumerate_the_dta_objects = () => dtaObjects.received(x=> x.GetEnumerator());
It should_call_workflow_host_helper = () => workflowService.AssertWasCalled(x => x.StartWorkflow());
}
With this configuration, my first test passes and my second test fails, as expected. I added a constructor to the class to inject the IWorkflowService.
public class GenerateAuthorisationWorkflows : IGenerateAuthorisationWorkflows
{
IWorkflowService _workflowService;
GenerateAuthorisationWorkflows(IWorkflowService workflowService)
{
_workflowService = workflowService;
}
public IList<Guid> FromDtaObjects(IList<DtaObject> dtaObjects, Employee requestingEmployee)
{
foreach (var dtaObject in dtaObjects)
{
Guid workflowKey = _workflowService.StartWorkflow();
}
return new List<Guid>();
}
public IList<Guid> FromDtaObjects()
{
return new List<Guid>();
}
}
Now, when I run the tests, they fail at the Because:
System.InvalidOperationException: Sequence contains no elements
at System.Linq.Enumerable.First(IEnumerable`1 source)
at MSpecTests.EmployeeRequestSystem.Tasks.Workflows.when_generate_workflows_is_called_with_a_dta_object_list_and_an_employee.<.ctor>b__4() in GenerateAuthorisationWorkflowsSpecs.cs: line 76
For clarity, line 76 above is:
Because of = () => result = subject.FromDtaObjects(dtaObjects, requestingEmployee);
I've tried tracing the problem but am having no luck. I have tried setting up a constructor that takes no arguments but it raises the same error. I have similar classes with IoC dependencies that work fine using MSpec/Rhino Mocks, where am I going wrong?
Castle Windsor requires a public constructor to instantiate a class. Adding public to the constructor allows correct operation.
public class GenerateAuthorisationWorkflows : IGenerateAuthorisationWorkflows
{
IWorkflowService _workflowService;
public GenerateAuthorisationWorkflows(IWorkflowService workflowService)
{
_workflowService = workflowService;
}
public IList<Guid> FromDtaObjects(IList<DtaObject> dtaObjects, Employee requestingEmployee)
{
foreach (var dtaObject in dtaObjects)
{
Guid workflowKey = _workflowService.StartWorkflow();
}
return new List<Guid>();
}
public IList<Guid> FromDtaObjects()
{
return new List<Guid>();
}
}
Rowan, looks like you answered your own question. It's good practice to explicitly state the access modifiers! By default, C# chooses private. These kinds of errors are easy to miss!
I can also see that your Establish block is too complicated. You're testing the implementation details and not the behavior. For example, you are
stubbing the GetEnumerator call that's implicitly made inside the foreach loop.
asserting that the workflow service was called only once
mixing MSpec automocking and your own local mocks
You're not actually testing that you got a GUID for every object in the input list. If I were you, I'd test the behavior like this...
public class GenerateAuthorisationWorkflows : IGenerateAuthorisationWorkflows
{
private readonly IWorkflowService _service;
public GenerateAuthorisationWorkflows(IWorkflowService service)
{
_service = service;
}
public List<Guid> FromDtaObjects(List<DtaObject> input, Employee requestor)
{
// I assume that the workflow service generates a new key
// per input object. So, let's pretend the call looks like
// this. Also using some LINQ to avoid the foreach or
// building up a local list.
input.Select(x => _service.StartWorkflow(requestor, x)).ToList();
}
}
[Subject(typeof(GenerateAuthorisationWorkflows))]
public class When_generating_authorisation_keys_for_this_input
: Specification<GenerateAuthorisationWorkflows>
{
private static IWorkflowService _service;
private static Employee _requestor = new Employee();
private static List<DtaObject> _input = new List<DtaObject>()
{
new DtaObject(),
new DtaObject(),
};
private static List<Guid> _expected = new List<Guid>()
{
Guid.NewGuid(),
Guid.NewGuid(),
};
private static List<Guid> _actual = new List<Guid>();
Establish context = () =>
{
// LINQ that takes each item from each list in a pair. So
// the service is stubbed to return a specific GUID per
// input DtaObject.
_input.Zip(_expected, (input, output) =>
{
DependencyOf<IWorkflowService>().Stub(x => x.StartWorkflow(_requestor, input)).Return(output);
});
};
Because of = () => _actual = Subject.FromDtaObjects(_input, _requestor);
// This should be an MSpec collection assertion that
// ensures that the contents of the collections are
// equivalent
It should_get_a_unique_key_per_input = _actual.ShouldEqual(_expected);
}