I have 2 tables in my database , one with cars and one with images for cars..is a one to many relationship..A car can have multiple images , but I want to select for every car just one image. The 2 tables are
Car table:
Schema::create('cars', function (Blueprint $table) {
$table->id();
$table->string('model');
$table->integer('seats');
$table->string('fuel');
$table->integer('year');
$table->string('color');
$table->string('gearbox');
$table->integer('price');
$table->string('coinType');
$table->timestamps();
});
Images table:
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->integer('car_id');
$table->string('file_name');
$table->timestamps();
});
class Car extends Model
{
protected $fillable = [
'model',
'seats',
'fuel',
'year',
'color',
'gearbox',
'price',
'coinType',
];
public function images()
{
return $this->hasMany(Image::class);
}
Image model:
class Image extends Model
{
protected $fillable = [
'car_id',
'file_name'
];
public function car()
{
return $this->belongsTo(Car::class);
}
I tried to make a join between tables like that:
$images = Image::join('cars', 'images.car_id', '=', 'car.id')
->select('images.file_name')
->first();
But I get only the first row from that table. I need some help here, Thank you
Related
I have made my research, but couldn't find the answer.
I have a Lightning App in Salesforce, I used LWC Js and Apex.
In one part of the app the user can add a 'desk item' (by typing its name) and select from a checkbox 1-2 items to add them to the 'desk'.
I used Apex to transfer the value of the 'desk item' to an Object and I can show it in a list (in the app).
How can I add the checkbox value(s) to the submitDesk(){...} so it sends its value(s) along with the 'desk item' value?
I don' know where/how exactly to add and to get it back?
The JS Code
import { LightningElement, track } from 'lwc';
import createDesk from '#salesforce/apex/FlexOfficeController.createDesk';
import getDesks from '#salesforce/apex/FlexOfficeController.getDesks';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class DeskList extends LightningElement {
// Desk
#track data_desks = [];
//table to show the desks's Id + Name, and the checkbox
columns = [
{ label: 'Id', fieldName: 'Id', type: 'text' },
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Accessories', fieldName: **the checkbox value**, type: 'text' }
];
// value to the picklist
connectedCallback(){
this.retreiveDesk();
}
retreiveDesk(){
getDesks({})
.then(d => {
this.data_desks = JSON.parse(d);
})
}
desk = {};
changeValue(event){
this.desk[event.target.name] = event.target.value
}
submitDesk(){
console.log(this.desk, this.value + 'Hi there');
createDesk({desk:JSON.stringify(this.desk)})
.then(data=> {
console.log(data + 'hello');
this.retreiveDesk();
// toaster
const evt = new ShowToastEvent({
title: "New desk",
message: `succefully created. Check out your reservation.`,
variant: "success"
})
this.dispatchEvent(evt);
})
}
// Checkbox
value = [];
get options() {
return [
{ label: 'Mouse', value: 'mouse' },
{ label: 'Screen', value: 'screen' },
];
}
// put the checkbox values into a string ('join')
get checkboxValues() {
console.log(this.value);
return this.value.join(',');
}
handleCheckboxChange(event) {
this.value = event.detail.value;
}
}
Apex Controller
public class FlexOfficeController {
#AuraEnabled
public static string createDesk(String desk){
try {
Desk__c d = (Desk__c)JSON.deserialize(desk, Desk__c.class);
insert d;
return d.id;
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
#AuraEnabled
public static string getDesks(){
try {
List<Desk__c> desks = new List<Desk__c> ();
desks = [SELECT Id, Name FROM Desk__c];
return JSON.serialize(desks);
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
}
HTML
<template>
<lightning-card>
<div class="slds-m-around_medium slds-theme_alert-texture">
<lightning-input name="Name" label="Name your desk" onchange={changeValue}></lightning-input>
<lightning-checkbox-group name="Accessories" label="Checkbox Group" options={options} value={value}
onchange={handleCheckboxChange}></lightning-checkbox-group>
<p>{checkboxValues}</p>
<lightning-button onclick={submitDesk} label="Submit"></lightning-button>
<lightning-datatable key-field="id" data={data_desks} columns={columns} hide-checkbox-column></lightning-datatable>
</div>
</lightning-card>
</template>
For Attribute i can make two table
1 is attributes and another is attribute_values
For attributes table
Schema::create('attributes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('attributeName')->unique();
$table->timestamps();
});
For attribute_values table
Schema::create('attribute_values', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('attributeId');
$table->string('value')->unique();
$table->timestamps();
});
I want to show like:
Under Size: L, S, M, XL etc
Under Color: Red, Green etc
What is the query ? and how can i apply ?
values is hasMany relationship
$attributes = Attribute::with('values')->get();
https://laravel.com/docs/8.x/eloquent-relationships#one-to-many
In the view
#foreach ($attributes as $attribute)
{{ $attribute->values->pluck('value')->join(', ') }}
#endforeach
https://laravel.com/docs/8.x/collections#method-pluck
https://laravel.com/docs/8.x/collections#method-join
I want to show contacts of an account, for that I have created LWC, I am calling Apex method here and I want to show all contacts of an account using data table, but data is not showing in the UI.
I am using custom label to pass account to Apex class.
please help me to achieve this
below is my code
JS Code:
const columns = [
{ label: "Name", fieldName: "Name" },
{ label: "Phone", fieldName: "Phone"},
{ label: "Email", fieldName: "Email"}
];
#track contactsList =[];
#wire(GetContacts,{AccountId:this.AccountId})
WireContactRecords({error, data}){
console.log('Entering WireContactRecords');
console.log('Entering WireContactRecords===='+this.AccountId);
if(data){
console.log('data*********+'+JSON.stringify(data))
this.contactsList = data;
this.error = undefined;
}else{
this.error = error;
this.contactsList = undefined;
}
}
Apex class
#AuraEnabled(cacheable = true)
public static Contact GetContacts(String AccountId){
String query = 'SELECT Name,Phone,Email FROM Contact WHERE AccountId =: AccountId';
return Database.query( query );
}
HTML CODE
<lightning-datatable
data={contactsList}
columns={columns}
key-field="id"
hide-checkbox-column>
</lightning-datatable>
The syntax to pass the value of a property defined in the JS class to a wired function is: #wire(functionName, { param: '$propertyName' })
Therefore, assuming that your class has an AccountId property, you have to change
#wire(GetContacts,{AccountId:this.AccountId})
to
#wire(GetContacts,{AccountId: '$AccountId'})
Moreover in the HTML you can use only property defined in your JS class, so if columns is defined only outside it, you should provide a getter:
get columns() {
return columns;
}
I want to get the name of the images in the trip version in show.blade.php
but for some reason I can't get someone to help me
App\Models\Images
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Images extends Model
{
use HasFactory;
protected $fillable = [
'id',
'name',
'trip_id',
];
public function trip()
{
return $this->belongsTo(Trip::class);
}
}
App\Models\Trip
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Trip extends Model
{
use HasFactory;
protected $fillable = [
'title',
'place',
'tripcontent',
'user_id'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function images()
{
return $this->hasMany(Images::class);
}
}
App\Http\Controllers\TripController
namespace App\Http\Controllers;
use App\Models\Trip;
use App\Models\Images;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Auth;
public function show(Trip $trip)
{
return view('trip.show')->with([
'trip' => $trip,
]);
}
resources\views\trip\show.blade.php
<div class="col-sm-6 col-md-4 col-lg-3 mt-2">
<img class="img-fluid" src="/img/trip/{{ $trip->images->name}}.jpg"">
</div>
That's how I want to get the data in view
$trip-> images-> name
Someone can help
I tried to save records of multiple products in a table, in database, with a single form but, there is this error and I don't know hot to solve it.
Error: Array to string conversion
in vendor\laravel\framework\src\Illuminate\Support\Str
$result .= (array_shift($replace) ?? $search).$segment;
Datatype of 'reference' and 'quantity' is string.
This is view:
<form action="{{route('carts.store')}}" method="post">
#csrf
#foreach(session('cart') as $id => $details)
<div class="form-group">
<input type=hidden class="form-control" name="reference[]" id="referenceNumber" value="{{ $details['reference'] }}">
</div>
<div class="form-group">
<input type=hidden class="form-control quantity" name="quantity[]" value="{{$details['quantity']}}" id="productPrice">
</div>
#endforeach
<button type="submit" class="btn btn-primary">Add products</button>
</form>
This is controller:
public function store(Request $request)
{
$cart = new Cart;
$data = [
'reference' => $request->reference,
'quantity' => $request->quantity
];
$cart->fill($data);
$cart->save();
return view('riepilogo');
}
When I click on button "add products" only the last records is saved in table
class Cart extends Model
{
protected $fillable = ['id', 'reference', 'pdv_code', 'quantity'];
public $timestamps = false;
public function product()
{
return $this->belongsToMany('App\Product');
}
}
class Product extends Model
{
protected $fillable = ['ean', 'reference', 'product_price', 'pdv_code'];
public $timestamps = false;
public function detail()
{
return $this->belongsTo('App\Products_detail');
}
public function cart()
{
return $this->belongsToMany('App\Cart');
}
}
> Blockquote
Migration:
public function up()
{
Schema::create('cart_product', function (Blueprint $table) {
$table->unsignedBigInteger('cart_id');
$table->foreign('cart_id')
->references('id')
->on('carts')
->onDelete('cascade');
$table->unsignedBigInteger('product_id');
$table->foreign('product_id')
->references('id')
->on('products')
->onDelete('cascade');
$table->primary(['cart_id', 'product_id']);
});
}
public function down()
{
Schema::dropIfExists('cart_product');
}
Migration cart:
public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->id();
$table->char('reference');
$table->integer('quantity');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('carts');
}
public function addToCart(Request $request, $id, $reference)
{
$product = Product::find($id)->where('reference', $reference)->first();
if(!$product) {
abort(404);
}
$cart = session()->get('cart');
// if cart is empty then this the first product
if(!$cart) {
$cart = [
$id => [
"id" => $product->id,
"quantity" => 1,
"price" => $product->product_price,
"ean" => $product->ean,
"reference" => $product->reference
]
];
//dd($cart);
session()->put('cart', $cart);
return back()->with('success', 'Product added to cart successfully!');
}
// if cart not empty then check if this product exist then increment quantity
if(isset($cart[$id])) {
$cart[$id]['quantity']++;
session()->put('cart', $cart);
return back()->with('success', 'Product added to cart successfully!');
}
// if item not exist in cart then add to cart with quantity = 1
$cart[$id] = [
"id" => $product->id,
"quantity" => 1,
"price" => $product->product_price,
"ean" => $product->ean,
'reference' => $product->reference
];
session()->put('cart', $cart);
return back()->with('success', 'Product added to cart successfully!');
}
Your form should have a reference to the cart via the id for both input fields
<form action="{{route('carts.store')}}" method="post">
#csrf
#foreach(session('cart') as $id => $details)
<div class="form-group">
<input type=hidden class="form-control" name="{{ 'cart_items[' .$id . '][reference]' }}" id="referenceNumber" value="{{ $details['reference'] }}">
</div>
<div class="form-group">
<input type=hidden class="form-control quantity" name="{{ 'cart_items[' . $id . '][quantity]' }}" value="{{$details['quantity']}}" id="productPrice">
</div>
#endforeach
<button type="submit" class="btn btn-primary">Add products</button>
</form>
$request->input('cart_items') will give the array of all products added to the cart
And you need another model CartItem and table cart_items to store the line items for the cart where each line can have a product_id and quantity at the very least.
Or you can add the quantity and price column on the cart_product pivot table.
For the carts table: you can have columns: total, tax etc the product reference and quantity columns can't be on carts table its of no use - a cart can have 3 products added for example to it [Tshirt: 1, Trouser: 2, Hoodie: 1] now which reference and which product's quantity will get stored in the carts table?
Instead there can be three records for cart_items table
Tshirt->id, quantity, cart_id
Trouser-id, quantity, cart_id
Hoodie->id, quantity, cart_id