I am making Web App in laravel 5.2....I have patient data stored in patient table(Patient Table does not contain doctor and area of treatment data) in database and then i have billing table which contains the data of patient's billing.In Billing table i want to retrieve the data from two columns(doctor_id and area_of_treatment_id) like i retrieved billing by defining relation in Patient Model...
I have already retrieve the patients along with their billing but i also need the doctor and area of treatment tables data by using their id stored in billing table....I have defined the relation of billing in Patient Model..Please help me to resolve my problem
Billing relation in Patient Model:
public function billing()
{
return $this->belongsTo(Billing::class,'mr','mr');
}
Patient Controller:
$patients = \App\Patient::with(['billing'])->get();
Patient Data along with billing:
You should also define the relations in Billing model:
public function doctor()
{
return $this->belongsTo(Doctor::class);
}
public function areaOfTreatment()
{
return $this->belongsTo(AreaOfTreatment::class);
}
Then you can eager load the objects with nested eager loading:
$patients = \App\Patient::with(['billing', 'billing.doctor', 'billing.areaOfTreatment'])->get();
Ref: https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
Related
I have two tables. Customer and address. The relationship of the table is that a CUSTOMER can have many ADDRESSES. So what I want as a result to my query is to get the list of customer and only one latest address
ADDRESS TABLE
id : 1
city:"cebu"
zip_code:"600"
cus_id:1
id:2
city:"mandaue"
zip_code:"6001"
cus_id:1
CUSTOMER TABLE
id: 1
name:"JOHN DOE"
What I want to get the customer "JOHN DOE" and the address with ID "2"
I'm using laravel query builder
If you want to get only one latest address, you can use hasOne same as :
// Customer model relation
public function lastestAddress()
{
return $this->hasOne(Address::class, 'customer_id')->orderBy('id', 'desc');
}
And
$model = Customer::with('lastestAddress')
you can use Eloquent ORM in laravel.
Eloquent :
You must setting in your customer model
Class Customer(){
public function address()
{
return $this->hasMany(Address::class, 'cuss_id', 'id')->latest();
}
in your Adress model :
Class Address(){
public function customer()
{
return $this->belongsTo(Customer::class, 'id', 'cuss_id')
}
Then in your controller you can call the model :
$data = Customer::with('address')->get();
So you have two tables: customers and addresses, with a "one customer can have many addresses" relationship.
In Laravel, we normally use Eloquent models to query the database. So to get a customer and all its addresses, we must first model the database; each table with its own Eloquent model. (See details in the docs.)
class Address extends Model
{
// although empty for now, this class definition is still important
}
class Customer extends Model
{
/**
* Get the latest address.
*/
public function currentAddress()
{
return $this->hasOne(Address::class, 'cus_id')->latestOfMany();
}
}
In the Customer model, our currentAddress() method defines how a Customer instance related to the Address instances.
It's like we're saying,
"A customer may have many Addresses. Just get one which is the latestOfMany. That's how we'll get the customer's currentAddress.
Now that we have the necessary Eloquent models setup, we can lookup John Doe and his current address.
$johnDoeId = 1;
// query the database for customer 1, including its current address
$johnDoe = Customer::with('currentAddress')->find($johnDoeId);
$johnDoe->currentAddress; // 👈 John's latest address, at Mandaue
I created an invoice form which has a section where users can dynamically add (via jquery row add) items to be invoiced.
I need to save these data into two tables: Invoice and Invoiceitems. The two tables have one to many via MySQL relationship and Laravel models have hasMany and belongsTo relation assigned.
My question is how to save the data into Invoiceitems table.
In your App\Invoice, define your relationship with App\InvoiceItem as follows:
public function items()
{
return $this->hasMany(InvoiceItem::class);
}
In your App\InvoiceItem model, define your relationship with App\Invoice as follows:
public function invoice()
{
return $this->belongsTo(InvoiceItem::class);
}
To create an Invoice with many InvoiceItem, you would then do something like this:
$invoice->items()->saveMany([
new App\InvoiceItem(['title' => 'iPhone X']),
]);
Read more about Eloquent Relationships.
I am using backpack CRUD package to create my website project in laravel 5.2
I want to establish a relationship between two tables. First table is called customer and second table is called transaction. Each customer has many transaction(1:N relationship).
Customer table record:
ID Name
123456 xyz
Transaction table record:
ID CustomerID
101010 123456
I know that I have to specify the relation in the customer model. But, how can I display the result of the relationship in CRUD ?
You should have relationships on both the Transaction and the Customer models, so you can do $customer->transactions and $transaction->customer:
class Customer extends Model
{
/**
* Get the comments for the blog post.
*/
public function transactions()
{
return $this->hasMany('App\Transactions', 'CustomerID', 'ID');
}
}
and
class Transaction extends Model
{
/**
* Get the comments for the blog post.
*/
public function customer()
{
return $this->belongsTo('App\Customer', 'CustomerID', 'ID');
}
}
Spend some time in the Eloquent Relationships Documentation. It's really important to understand them if you want to be a Laravel developer.
In order to display the relationship in the CRUD, you can then use Backpack's select column type to display it in the table view and select or select2 field types to display it in the add/edit views. Read the CRUD Example Entity to better understand how that works.
First of all when you are creating migrations for both tables, table which contain Foreign Key (FK) must have field like this:
public function up(){
$table->increments('id');
$table->integer('customerID')->unsigned();
}
After that you are need to call next command into console
php artisan migrate
Next is going next commands:
php arisan backpack:crud customers
php arisan backpack:crud transactions
After that you need to define functions in models which returns values from other tables. Customer models need to have next function
public function transactions(){
return $this->hasMany('Transaction');
}
Transaction model must have next function
public function customer() {
return $this->belongsTo('Customer');
}
Next you must add CRUD field in Customer controller to display
transactions in select box.
$this->crud->addField([
'label' => 'Transactions', // Label for HTML form field
'type' => 'select2', // HTML element which displaying transactions
'name' => 'customerID', // Table column which is FK for Customer table
'entity'=> 'customer', // Function (method) in Customer model which return transactions
'attribute' => 'ID', // Column which user see in select box
'model' => 'Transaction' // Model which contain FK
]);
Hope this helps :)
After you built onetomany relationship with transaction, you can get the results.
$customer=Customer::where(['id'=>'123456'])->with('transaction')
->first();
print_r($customer->Name); // gives the customer name
foreach($customer->transaction as $cid)
{
print_r($cid->CustomerID); // gives the customer id
}
Laravel Relationships Documentation is always helpful. Go through it.
I have a default authentication table user and another table user_profiles
user(id,email,password)
user_profiles(id,first_name,last_name,mobile)
i am connecting these two table using a many-to-many relationship
for this, i added relationship in the both model class- User and UserProfile
// User Model
public function userProfiles()
{
return $this->belongsToMany('App\Models\UserProfile', 'user_user_profile',
'user_profile_id', 'user_id');
}
//UserProfile Model
public function users()
{
return $this->belongsToMany('App\User', 'user_user_profile',
'user_profile_id', 'user_id');
}
and i tried to access the UserProfle details via user table using
$user=\App\User::find(1)->userProfiles()->get();
but not working and also tried
/$user = \App\User::findOrFail(1)->with('userProfiles')->get();
that is also not working , please help to
Get the user_profile table details along with user table
How to access the Pivot table(user_id,user_profile_id) value
How to display these data from multiple tables into a view form?
You have defined the relationship wrong in your User Model: swap user_id and user_profile_id
// User Model
public function userProfiles()
{
return $this->belongsToMany('App\Models\UserProfile', 'user_user_profile',
'user_id' , 'user_profile_id');
}
I have a GiftCards table in my DBML that has a related property called Audit. The Audits are stored in a separate table. Each Audit has a related Person associated to it. There is also a Persons table. The relationships are set up and are valid in my DBML.
The problem is that when I instantiate a new Gift Card I also create a new related Audit in the OnCreated() method. But at the same time, I also create a related Person when I instantiate a new Audit. The Person is the current user. Actually the Audit's OnCreated method checks if the user already exists.
The problem is that when I instantiate a new gift Card, it also creates an associated Audit, which is fine, and the Audit creates an associated Person. But the Person already exists in the database. When I look at the data context's GetChangeSet(), it shows 3 inserts. The Persion should not show as an insert because he already exists in the database.
Here is how I implemented this. It is an MVC application where the Controller receives a gift card:
[HttpPost]
public ActionResult Save(GiftCardViewModel giftCard)
{
if (ModelState.IsValid)
{
GiftCard gc = GiftCardViewModel.Build(giftCard);
repository.InsertOrUpdate(gc);
repository.Save();
return View("Consult", new GiftCardViewModel(repository.Find(gc.GiftCardID)));
}
else
SetupContext();
return View("_Form", giftCard);
}
The Gift Card has:
partial class GiftCard
{
partial void OnCreated()
{
// Set up default audit.
this.Audit = new Audit();
}
}
The Audit class has:
partial void OnCreated()
{
// Setup timestamp
this.Timestamp = DateTime.Now;
this.Person = Person.GetPerson(Membership.GetUser().UserName);
}
And finally, my Person class has:
public static Person GetPerson(String username)
{
using (GiftCardDBDataContext database = new GiftCardDBDataContext())
{
// Try to get the person from database
Person person = database.Persons.SingleOrDefault(personData => SqlMethods.Like(personData.Username, username));
if (person == null)
{
person = new Person()
{
Username = username,
FullName = "Full name TBD"
};
database.Persons.InsertOnSubmit(person);
database.SubmitChanges();
}
// Return person data
return person;
}
}
When I create a new gift card, I always get an error saying that it's attempting to insert a duplicate person in the Persons table. I don't understand because my static class specifically checks if the Person already exists, if yes, I return the Person and I don't create a new one. Yet, the GetChangeSet() shows three inserts including the Person, which is wrong.
What am I doing wrong here?
I believe your issue here is that you're using multiple contexts. You have one being created by your repository, and another is created in the static method on your Person object. You also aren't making any effort to attach the Person created/retrieved from the other context to the context of your Audit class.
You should look at a single unit of work, a single DataContext class, and perform all your work in that.