How do I connect a "related products" table - mysql

I have the following tables
products table
product_id
name
desc
with a has many relation to
suggested products table
id
product_id
suggested_product_id
Quantity
required (boolean)
What I am trying to accomplish is being able to access the name of a suggested product id in my view.
Products Controller
public function show($id)
{
$product = Product::with('stockitems','suggestedproducts.product')->find($id);
return view('backend.products.show', compact('product'));
}
I know the issue is at "suggestedproducts.product" just not sure how i specify the key(suggested_product_id) for the eager load is a product_id.

You should define the following relationship in your Product model:
public function suggestedProducts()
{
return $this->belongsToMany(Product::class, 'suggestedproducts', 'product_id', 'suggested_product_id')
->withPivot(['quantity', 'required']);
}
This would allow you to get all related products as Eloquent models by doing the following:
$product = Product::with('suggestedProducts')->find($id);
$product->suggestedProducts; // This accesses the suggested products
To access the name of each suggested product, just do the following:
foreach ($product->suggestedProducts as $suggestedProduct)
echo $suggestedProduct->name;
To access the data in the pivot table, you have to use the following:
foreach ($product->suggestedProducts as $suggestedProduct)
echo $suggestedProduct->pivot->quantity;

Related

How to join two table in laravel 8 with no duplicate

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

problem with Using pivot table with Eloquent and Laravel

Here is my problem. I have a table called user and table called skills, also I have a pivot table that connects these two called EmployeeSkill. I am trying to fetch the skills that belong to the user but when i use tinker it returns Base table or view not found: 1146 Table 'pfe_sirh_db.skill_user' doesn't exist (SQL: select skills.*, skill_user.user_id as pivot_user_id, skill_user.skill_id as pivot_skill_id, skill_user.employee_id as pivot_employee_id from skills inner join skill_user on skills.id = skill_user.skill_id where skill_user.user_id = 1)' and am using swagger by the way it returns this "withTimestamps": false
class User extends Authenticatable{
protected $table = "users";
public function skills()
{
return $this->belongsToMany(Skill::class);
}
}
and
class Skill extends Model
{
public function User()
{
return $this->belongsToMany(User::class);
}
}
and the pivot table
class EmployeeSkill extends Model
{
protected $table = "employee_skills";
protected $fillable = [
'employee_id', 'skill_id', 'note'
];
}
Your pivot table should be named skill_user (singular) following the model name they belong to. And you don't need a EmployeeSkill model for this relation to work, you only need the table.
As said in the documentation:
to determine the table name of the relationship's joining table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method
And then you should exclude this line:
protected $table = "employee_skills";
change your table name to skill_user
And in your pivot table you should use user_id as a foreign key
You can retrieve all skills from a user by doing this:
$user = User::find(1);
$user->skills();
This will give you all the skills from the user with the id 1
Be aware that you can use any table name and any foreign key name but if you do that you need to specify the names on the relations. So i recommend you doing what i 've told you, since is the standard way

Using foreign key to get all product from another table?

I have two table Order_table and Invoice_table ,i have order_id of Order_table which is foreign key of Invoice_table.
How to write the query in this situation in Laravel.
You should rather try to use eloquent relationship for this sort of problem. You can see here for the reference https://laravel.com/docs/5.6/eloquent-relationships#one-to-one
As you said you should only include _"order_id"_ column in your invoices databse table.
In your Order.php model, write this code:
public function invoice()
{
return $this->hasOne('App\Invoice');
}
In your Invoice.php model, write this code:
public function order()
{
return $this->belongsTo('App\Order');
}
and from the Controller you can use the eloquent query to get data. For example, you can get random 3 data using this code:
$results = Invoice::limit(3)->get();
echo $results->order;
If we suppose that the name of the models are Invoice and Order, you can use this code :
$invoice = Invoice::find($invoice_id);
$orders = $invoice->orders();

Relationships between tables in laravel using backpack package

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.

How can joins be nested in Laravel 4.2 Query Builder

I am trying to get a products list using Laravel 4.2 query builder.
The tables are related as follows
PRODUCTS
products.product_category_id
PRODUCT CATEGORIES
products.product_category_id = product_categories.id
PRODUCT CATEGORY TRANSLATIONS
product_categories.id = product_category_translations.product_category_id
What I am doing now is...
$products = DB::table('products')->join('product_categories', function($join){
$join->on('products.product_category_id','=','product_categories.id');
});
And I can get the contents of the product categories related table. But how can I nest another join and get the related data from the product categories translations table?
I would advise you to take a look at the laravel documentation to find a proper way to make relationship with models.
http://laravel.com/docs/4.2/eloquent#relationships
You would then create models like
class Product extends Eloquent {
public function category()
{
return $this->hasOne('ProductCategory');
}
}
class ProductCategory extends Eloquent {
public function product()
{
return $this->hasOne('Product');
}
public function translation()
{
return $this->hasOne('Translation');
}
...
Then to fetch the last table it would be as simple as something like :
$category = Category::find($categoryId);
$translation= $category ->translation;
Or if the id you have, is the productId, you can make it similar from the product table.