how to use hasOne for two other detail models in laravel - database

I have one main table and two detail tables
table names: tb_main, tb_detail1, tb_detail2
tb_main
id, detail_code
tb_detail1
id, main_id
tb_detail2
id, main_id
I want get detail data using one function in main model
public function detail()
{
if(detail_code == 1)
return $this->hasOne(Detail1::class, 'main_id', 'id');
else
return $this->hasOne(Detail2::class, 'main_id', 'id');
}
Any ideas? please help me!
And sorry for my bad English.

You can use $this->detail_code
public function detail() {
if($this->detail_code == 1) {
return $this->hasOne(Detail1::class, 'main_id', 'id');
}else{
return $this->hasOne(Detail2::class, 'main_id', 'id');
}

Don't do that in the relation method. First, declare all relations in the main model like so:
public function detail1()
{
return $this->hasOne(Detail1::class, 'main_id');
}
public function detail2()
{
return $this->hasOne(Detail2::class, 'main_id');
}
Then write one method to decide what to do based on detail_code :
public function detail()
{
if($this->detail_code == 1)
return $this->detail1()->first();
return $this->detail2()->first();
}

Related

Restriction on duplicate entry with respect to another column entry

I have two models Member and Saving with
Member('id','name')
Saving('id','member_id','amount','month')
I have to restrict duplicate entry of saving of a member for a given month.
Member.php
class Member extends Model
{
protected $fillable=['name','address','phone'];
public function loan()
{
return $this->hasOne(Loan::class,'member_id','id');
}
public function savings()
{
return $this->hasMany(Saving::class,'member_id','id');
}
}
Saving.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Saving extends Model
{
protected $fillable=['amount','month','member_id'];
public function member()
{
return $this->belongsTo('App\Member','member_id','id');
}
}
Is it possible to implement restriction, using functions in model, or controller?
EDIT:
this is how i tried.
SavingController.php
public function addSaving(Request $request){
if($request->isMethod('get')){
$memberData = Member::all();
return view($this->_pagePath.'saving.addsaving',compact('memberData'));
//return redirect()->back();
}
if($request->isMethod('post')){
$this->validate($request,[
'amount' => 'required',
'month' => 'required'
]);
$data['amount'] = $request->amount;
$data['month'] = $request->month;
$data['member_id']= $request->name;
$member= Member::find(1);
if($member->savings()->where('month',$request->month)->exists())
{
return 'Savings for this month are already added.';
}
else
{
if(DB::table('savings')->insert($data)){
return redirect()->route('saving')->with('success','data was successfuly inserted');
}
}
}
}
An enum is a wrong column for month my friend, unless you don't care for the year. Because this way you will just be able to store savings for each month, but not for each year separately.
Your relationship is set correctly, so you can then make a check like this:
// considering you have the specific member selected
$member = Member::find('ID_OF_THE_MEMBER');
if($member->savings()->where('month', APRIL)->exists())
{
return 'Savings for this month are already added.';
}

ErrorException (E_NOTICE) Undefined offset: 0 laravel

I am trying to read from the database and display data into a form but I Keep getting this error.
This is my controller:
public function create()
{
/* this function gets data from the database (marks table) and render it to the view view */
$data['data']=DB::table('marks')->get();
if(count($data[0])>0){
return view('view',$data);
}
else{
return view('view');
}
}
And this is how I have defined the route:
Route::resource('claude', 'viewcontroller');
The variable $data doesn't have an index of 0.
But it has a key called data.
So you have to access it via the key.
It should be
if(count($data['data']) > 0){
return view('view',$data);
}
get() will return a collection, you can check if its has items by
if ($data['data']->count()) {
return view('view',$data);
} else {
return view('view');
}
if(is_array($data) && isset($data)){
return view('view',$data);
}

How to check model column exist in cakephp2 or not?

public function beforSave($option = array()) {
if($this->columnName) {
// Statement
}
}
Something like that
if(!$this->loadModel($type)) {
// Statement
}
Get the model schema
$this->modelName->schema();
Check if my field is available or not
if (!empty($this->modelName->schema('date_created'))) {
// statement
}
Or
public function beforeSave($options = array()) {
if ($this->hasField('date_created')) {
$this->data[$this->alias]['date_created'] = date('Y-m-d H:i:s');
}
}
Try with getColumnType and array_key_exist;
getColumnTypes() Returns an associative array of field names and column
types.
$fileds = $this->YourModelName->getColumnTypes();
if(array_key_exists('columnName', $fileds)) {
// Statement
}

laravel 5 display books with author name

How do I display books with the author name?
Here is my model:
Book.php
public function authors()
{
return $this->belongsTo('App\Author');
}
Author.php
public function books()
{
return $this->hasMany('App\Book');
}
My controller:
BookController.php
use App\Author;
public function index()
{
foreach (Book::with('authors')->get() as $book)
{
echo $book->authors->name;
}
}
ERROR
Trying to get property of non-object
Please HELP what might be the problem?
Your code will display only author name for each book.
Instead use this code that returns all books with authors.
public function index()
{
$books = Book::with('author')->get();
return $books;
}

CakePHP - How to check in beforeSave if it's an INSERT or UPDATE

In my model's beforeSave method, how can I check if the save operation is going to be an INSERT or an UPDATE?
I want to add to the model data, but only if it's inserting a new row.
You can just check in the data if the id exists:
function beforeSave($options = array())
{
if(empty($this->data[$this->alias]['id']))
{
//INSERT
}
else
{
//UPDATE
}
}
This is how you would do in Cakephp 4 (in case someone is looking for it)
EDIT it also applies to Cakephp 3 as BadHorsie stated
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)
{
if ($entity->isNew()) {
//INSERT
}else{
//UPDATE
}
}
You can try this
public function beforeSave($options = array()) {
if($this->id) {
// Update
} else {
// Add
}
}

Resources